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.innerHTMLand 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
itag in there.Using
textContentinstead oftextalso 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.