Search code examples
javascriptdomgetelementsbytagname

How to get only matched element in DOM when using getElementByTagName?


I want to get one element in the content that its innerHTML is "SOMETHING". The tag name is

<div>

and it does not have id.

<div class="hfvbuerfv iygerifyg r">
   <div class="iyg8ybwef g irfg">
      <div class="oiuh9 iyg y">SOMETHING</div>
      <div class="iojuiohi"></div>
   </div>
</div>

I tried this:

var all = document.getElementsByTagName("div");
for (i=0; i<all.length; i++) {
   if (all[i].innerHTML.toString().includes("SOMETHING")) {
      console.log(all[i]);
   }
}

but I also get all parent div.

Consider that, I don't want to use JQuery or XPATH. I just want to do it with pure javascript.


Solution

  • The reason you get all parent nodes as well because the innerHTML of the parent nodes contains the div node with SOMETHING in it. I think you need to add a check that the only child of the matched div node is a text node and that contains the nodeValue of "SOMETHING":

    function findSomethingNode() {
      var allDivs = document.getElementsByTagName('div');
    
      for (var i = 0; i < allDivs.length; ++i) {
        // Check for a single child that is a text node
        // (nodeType === 3) that has the text (nodeValue) "SOMETHING"
        if (allDivs[i].childNodes.length === 1 && allDivs[i].childNodes[0].nodeType === 3 && allDivs[i].childNodes[0].nodeValue === "SOMETHING") {
          return allDivs[i];
        }
      }
    }
    
    // This logs the found node
    console.log(findSomethingNode());
    <div class="hfvbuerfv iygerifyg r">
      <div class="iyg8ybwef g irfg">
        <div class="oiuh9 iyg y">SOMETHING</div>
        <div class="iojuiohi"></div>
      </div>
    </div>