0

I'm trying to check if an element doesn't contain a specific sentence.

<div id="element">Hey there, This is the element I want to check if it doesn't contain specific text</div>

<script>

    var element = document.getElementById('element');

    if( element.textContent == 'hello world' < 0 ){
        console.log('The element doesn't contain this sentence');
    }else{
        console.log('The element contain this sentence');
    }

</script>

So if the element with id element doesn't contain hello world, I if statement should be executed. And if the element contains the text hello world the else statement should be executed.

This should also work if I check a sentence that does exist like Hey there, Then the else statement should be executed.

  • You are looking for the [`indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) property. – Ibu Aug 06 '19 at 00:06

3 Answers3

2

Your condition:

element.textContent == 'hello world'

doesn't test if the text contains the text. It tests if it equals the text.

A better test would be:

element.textContent.includes('hello world')

However since includes isn't supported on IE and polyfills for this is unneccesary we can use indexOf:

element.textContent.indexOf('hello world') > -1
Achtung
  • 682
  • 3
  • 16
0

You can use includes() to check for possible match.

let str = 'hello world';
console.log(str.includes('hello world'));
console.log(str.includes('hello worlds'));
Nidhin Joseph
  • 9,981
  • 4
  • 26
  • 48
0

indexOf is your friend.

Here is your code changed a little

<div id="element">Hey there, This is the element I want to check if it doesn't contain specific text</div>

<script>

    var element = document.getElementById('element');

    if( element.textContent.indexOf('hello world') < 0 ){
        console.log("The element doesn't contain this sentence");
    }else{
        console.log('The element contain this sentence');
    }

</script>
Jurion
  • 1,230
  • 11
  • 18