Reputation: 3
I have a list of span elemets with values:
<span>Example1</span>
<span>Example2</span>
<span>Example3</span>
<span>Example4</span>
<span>Example5</span>
How would I be able to check if there is a span with for example "Example4" inside?
I've tried the following yet with no result:
if($('span').textContent = value){
console.log('exists');
}
if($('span').html(value){}
if($('span').html(value).length > 0){}
but they always return true..
Thanks for reading :)
Upvotes: 0
Views: 1262
Reputation: 5463
The Array method some
(IE9+) returns true if any member matches the given condition:
var matched = $('span').toArray().some(function(node) {
return node.innerHTML == 'Example4';
});
Upvotes: 0
Reputation: 104
Please test it first and use it to fit your code block.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="jquery-1.7.1.js"></script>
<script type="text/javascript">
function createElement123(){
if ( $('span:contains("Example4")').length > 0 ) {
alert('Exists');
} else {
alert('Not Exists');
}
}
</script>
</head>
<body>
<input type="button" onclick="createElement123()" value="Check Text Exists"/>
<span>Example1</span>
<span>Example2</span>
<span>Example3</span>
<span>Example4</span>
<span>Example5</span>
</body>
</html>
Hope that it will help you to solve your problem.
Upvotes: 0
Reputation: 145458
There is a :contains
selector:
if ( $('span:contains("Example4")').length > 0 ) { ... }
However this approach will fail if there are <span>
elements with text like "Example 40"
. For strict comparison you may use trick with a .filter
method:
if ( $('span').filter(function() {
return $.trim($.text(this)) === 'Example4';
}).length > 0 ) { ... }
Upvotes: 4