I need to search my entire document for a phone number, and compile a list of elements which have this phone number in them.
However I have encountered afew snags.
I can't simply do
document.body.innerHTML
and replace the numbers, as this messes up third party scripts.The following will match the elements, but ONLY if they have the number within them, and nothing else:
let elements = document.querySelectorAll("a, div, p, li"); let found = []; for (let elm in elements) { if (elements.hasOwnProperty(elm)) { if (elements[elm].textContent !== undefined && elements[elm].textContent.search("00000 000000") != -1) { found.push(elements[elm]); } } }
So the following element will not match:
<li class="footer__telephone"> <i class="fa fa-phone" aria-hidden="true"></i>00000 000000 </li>
Due to having the
i
tag in there.Using
textContent
instead oftext
also does not work as the parent of an element will then match, but I don't want the parent.
Edit:
<div class="row-block hmpg-text">
<div class="wrapper">
<div class="container">
<div class="row">
<div class="twelvecol">
00000 000000
</div>
</div>
</div>
</div>
</div>
Lets say the above is my HTML, if I loop through all the elements and test them with testContent
then the first is going to be returned as true, to containing my number, but I need the element with the class of twelvecol
on it, not the parent which is 4 levels up.