Search code examples
javascriptarraysgetelementsbytagname

How to get the id of <a> element inside <h2> element in JS?


Consider the following example:

<h2><a id="anchorid"><a/> Hello world!</h2>

I am trying to get the text inside and the id of a. At this point I only get the text but the id is undefind. The question is how to get the id of the element inside another element?

Bellow my attempts:

  var anchor = document.getElementsByTagName("h2"); //take all h2
  var headings = Array();
  headings.push(anchor)

  for (var i = 0; i < anchor.length; i++) {
    var c = document.body.children; //take all children, hopegully anchors
    if (c.nodeName == "A"); { //if the el is anchor
      var id = c.id; // get the the id of each anchor
      var text = "";
      var text = anchor[i].innerHTML;
      // if(id!="" ){
      document.write("<br>----------------------------Id of anchor- " + id + "<br>Text of h2--" + text + "<br>------------------------");
    }
  }

In my file there are many headings for this reason i put them in an array() so I can loop and display the text for everyone.

Please, provide some suggestions! Your help will be much appreciated


Solution

  • Refined your code and fixed used variables a bit and:

    var anchor = document.getElementsByTagName("h2"); //take all h2
    
    for (var i = 0; i < anchor.length; i++) {
    
      var children = anchor[i].children; //take all children, hopegully anchors  
      for (var ch = 0; ch < children.length; ch++) {
        var c = children[ch];
        if (c.nodeName == "A"); { //if the el is anchor    
          var id = c.id; // get the the id of each anchor
          var text = "";
          var text = anchor[i].innerHTML;
          console.log(id, text);
        }
      }
    }
    <h2>
      <a id="anchorid">Hello world!</a></h2>

    But note that this will only work for the immediate children of h2 tags.