如何获取<a> element inside </a> <h2> <a> element in JS?

时间:2018-02-08 10:10:56

标签: javascript arrays getelementsbytagname

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

2 个答案:

答案 0 :(得分:1)

我认为你可以用更少的代码实现目标。

var i, anchors = document.querySelectorAll('h2 > a');
for (i = 0; i < anchors.length; i += 1) {
    var a = anchors[i];
    console.log(a.id, a.parentElement.innerText);
}

如果您不确定,a是h2的第一个孩子,您可以使用以下选择器:

document.querySelectorAll('h2 a');

答案 1 :(得分:-1)

优化您的代码并修改使用过的变量并且:

&#13;
&#13;
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);
    }
  }
}
&#13;
<h2>
  <a id="anchorid">Hello world!</a></h2>
&#13;
&#13;
&#13;

但请注意,这仅适用于h2代码的直接子项。