Lets say we have a custom attribute named data-content. Now lets look for the html markup :
<h1 data-content="one two three four">Hello</h1>
I want a Javascript / jQuery function that can do something like this :
verify.contains("h1", "two"); // => true
verify.contains("h1", "five"); // => false
Or
$("h1").verifyContains("two"); // => true
$("h1").verifyContains("five"); // => false
So, how to do it ?
Using Attribute Contains Word Selector
var verify = {
contains: function(selector, content) {
return Boolean($(selector + '[data-content~=' + content + ']').length)
}
}
console.log(verify.contains("h1", "two"))
console.log(verify.contains("h1", "five"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 data-content="one two three four">Hello</h1>
Jquery plugin function
$.fn.verifyContains = function(content) {
return $(this).is('[data-content~=' + content + ']')
}
console.log($("h1").verifyContains("two"))
console.log($("h1").verifyContains("five"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 data-content="one two three four">Hello</h1>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments