Get Elements Containing Text From Array
I want to search all the elements containing any string in the array. For example I have following list of items
- cricket bat
- tenn
Solution 1:
You can use :contains
pseudo-selector:
Select all elements that contain the specified text.
$('li:contains("bat"), li:contains("ball")')
Solution 2:
You can use :contains selector.
I think you meant either one of those values, in that case
var arr = ['bat', 'ball'];
var selectors = arr.map(function(val) {
return':contains(' + val + ')'
});
var $lis = $('ul li').filter(selectors.join());
$lis.css('color', 'red')
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><ul><li>cricket bat</li><li>tennis ball</li><li>golf ball</li><li>hockey stick</li></ul>
Solution 3:
Try this:
$.each(["bat", "ball"], function (i,val) {
if ($("ul li:contains(" + val + ")").length) {
$("ul li:contains(" + val + ")").css('color', 'red')
}
})
Solution 4:
Try utilizing .filter()
, .match()
var arr = ["bat", "ball"];
var res = Array.prototype.filter.call(document.querySelectorAll("li")
, function(el, index) {
return el.textContent.match(newRegExp(arr.join("|"))) !== null
});
console.log(res);
<ul><li>cricket bat</li><li>tennis ball</li><li>golf ball</li><li>hockey stick</li></ul>
Post a Comment for "Get Elements Containing Text From Array"