Check if DIV contains a particular text/word using JavaScript

← PrevNext →

In JavaScript, you can use the .includes method to check if a string contains a particular string or text. Similarly, the .includes() method can be used to check if a DIV element (or any element) contains a particular text or word in it. In-fact, I have shared two different methods here.

Syntax .includes() Method

string.includes(value, start)

.includes() returns a Boolean value (true or false). It takes two parameters. 1st parameter is the value or the string that you want to search. 2nd parameter is the position you want to start the search.

Do you know 👉 you can use the .includes() method to search an array like an SQL LIKE statement. Check this out.

Example

<body>
  <div id='cont'>
    The colour Red is linked to Passion and Love
  </div>
</body>

<script>
  let ele = document.getElementById('cont');
  
  // check if DIV contains the word "Passion".
  if (ele.innerHTML.includes('Passion')) {
    document.write ('The colour is Red');
  }
</script>
Try it

Related Article

How to check if textarea contains a particular word using JavaScript?

The <div> has a string of words and looking for the word "Passion". Remember, the string that you provide must match the word inside the element. So, the P in Passion is capital and that’s how it must be included inside .includes().

Similarly, you can use the include() method with a string to search for a string or text. For example,

<script>
  const str = 'The colour Red is linked to Passion and Love';
  document.write (str.includes('Red'));		// output: true;
</script>

Using indexOf() to check if DIV contains a Word

Here’s another method that you can use to check if a <div> a text or word. The method is .indexOf().

I have shared an article here before explaining about How to use JavaScript .indexOf() method to check if a URL contains a specified string or text. You must read it.

Syntax of indexOf()

string.indexOf(value)

So, how do you we apply the method to check if a word or a particular text contains in a <div> element? Like this…

<body>
    <div id='cont'>
        Bells Sparrow <br />
        Bald Eagle
    </div>
</body>

<script>
  const ele = document.getElementById('cont');
  
  if (ele.innerHTML.split(/\s+/).indexOf('Eagle') > 0) {
    document.write ('<br /> The list has Eagle');
  }
</script>
Try it

← PreviousNext →