Sometimes, we want to check if any div contains a word with JavaScript.
In this article, we’ll look at how to check if a any div contains a word with JavaScript.
Check if Any div Contains a Word with JavaScript
To check if a div contains a word with JavaScript, we can select all the divs and then loop through them with the for-of loop.
Then we can get the text content of each div in the loop body using the textContent
property.
And then we can check if the div includes the text we’re looking for with the JavaScript string’s includes
method.
For instance, if we have:
<div class='titanic'>
foo
</div>
<div class='titanic'>
bar
</div>
<div class='titanic'>
baz
</div>
Then we can check which div has the word ‘bar’ in it by writing:
const divs = document.querySelectorAll('div')
for (const d of divs) {
if (d.textContent.includes('bar')) {
console.log('has bar')
}
}
We select all the divs and assign it to divs
with:
const divs = document.querySelectorAll('div')
Then we loop through the node list object we assigned to divs
by writing:
for (const d of divs) {
if (d.textContent.includes('bar')) {
console.log('has bar')
}
}
We get the text content of each div with d.textContent
.
Then we call includes
with 'bar'
to check if the text content of the div includes 'bar'
.
If that’s true
, we log 'has bar'
.
Therefore, we should see 'has bar'
logged once in the console since ‘bar’ appears in one div.
Conclusion
To check if a div contains a word with JavaScript, we can select all the divs and then loop through them with the for-of loop.
Then we can get the text content of each div in the loop body using the textContent
property.
And then we can check if the div includes the text we’re looking for with the JavaScript string’s includes
method.