Jquery - select element with specific content
I have an html structure like this:
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
...
<div class="test">
<span class="content">100</span>
</div>
In my javascript code, I need to get an element <span>
with a class content
that has exactly 1
or 2
, ...,100
I tested the jquery .contains
method , but this returns all elements that have for example 1
. such as 1
, 12
, ... .
source to share
You can use a method filter
that takes a callback function to apply to each item.
var array=$('.test').find('.content').filter(function(){
return $(this).text().trim()==100;
});
console.log(Array.from(array));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
<div class="test">
<span class="content">100</span>
</div>
source to share
You can proceed as follows:
$('.content').each(function(){
if($(this).html() == "2")
{
console.log("THE SPAN WITH 2 IS ");
console.log($(this)[0]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
<div class="test">
<span class="content">100</span>
</div>
What we're doing here is check the spans content class and check if their inner html is 2 and if this is us its console.
source to share
You can use vanilla's .indexOf () method .
The indexOf method takes a parameter of the string you want to find and returns either the index (if found) or -1 if not.
var myEl = document.querySelector(".test"):
for loop...
if( myEl.innerHTML.indexOf(2) != -1 ){
console.log("This element contains the number 2")
}
source to share
You can use .filter()
, get and check .textContent
or an .innerHTML
item, in the callback .filter()
you can use RegExp
N$
where the N
number matches. For example, to match items that have "1"
or "2"
are set to .textContent
, you can use RegExp
/1$|2$/
; to match "100"
, /100$/
; fromRegExp.prototype.test()
var filtered = $("span.content").filter((_, {textContent}) =>
/1$|2$/.test(textContent));
filtered.css("color", "green");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
...
<div class="test">
<span class="content">100</span>
</div>
source to share