How to access HTML element without ID?

后端 未结 6 1540
暖寄归人
暖寄归人 2020-11-30 05:39

For instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)?

&
6条回答
  •  野性不改
    2020-11-30 06:26

    function findFirstDescendant(parent, tagname)
    {
       parent = document.getElementById(parent);
       var descendants = parent.getElementsByTagName(tagname);
       if ( descendants.length )
          return descendants[0];
       return null;
    }
    
    var header = findFirstDescendant("header-inner", "h1");
    

    Finds the element with the given ID, queries for descendants with a given tag name, returns the first one. You could also loop on descendants to filter by other criteria; if you start heading in that direction, i recommend you check out a pre-built library such as jQuery (will save you a good deal of time writing this stuff, it gets somewhat tricky).

提交回复
热议问题