Question

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 :)

Was it helpful?

Solution

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 ) { ... }

OTHER TIPS

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.

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';
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top