如何获取在父标记之前显示的textContent?

时间:2017-07-20 20:42:53

标签: javascript html javascript-events

我正在尝试获取显示在父div标签上方的h3标签的textContent。代码重复,添加id不是h3标签的选项。希望在纯JavaScript中执行此操作。我的html目前是......

<h3>Some header</h3> //textContent I am trying to get.
<div class="panel panel-success"> //parent
    <div id="someid" class="panel-heading"></div> //child
    <span class="pull-right glyphicon glyphicon-list-alt" style="padding-right: 1%"
                      onclick="myFunc(this.parentNode.id, what.goes.here?)"></span> //this needs to return parent id and the value of h3 tag
</div> 
<h3>Some other header</h3> //textContent I am trying to get.
<div class="panel panel-success"> //parent
    <div id="someid" class="panel-heading"></div> //child
    <span class="pull-right glyphicon glyphicon-list-alt" style="padding-right: 1%"
                      onclick="myFunc(this.parentNode.id, what.goes.here?)"></span> //this needs to return parent id and some other tag when this span button is clicked
</div>
<h3>yet another header</h3> //textContent I am trying to get.
<div class="panel panel-success"> //parent
    <div id="someid" class="panel-heading"></div> //child
    <span class="pull-right glyphicon glyphicon-list-alt" style="padding-right: 1%"
                      onclick="myFunc(this.parentNode.id, what.goes.here?)"></span> //this needs to return parent id and yet another header when clicked.
</div>  

这段代码重复多次,h3的textContent和div id每次都会改变。我试图返回h3标签的textContent的值,该标签出现在我点击相对于点击期间出现的div标签的span按钮上。 h3标记不是任何其他父/子关系的一部分,并且代表......

3 个答案:

答案 0 :(得分:1)

click的{​​{1}}处理程序,您可以像这样访问上述span元素:

h3

请参阅:https://developer.mozilla.org/en/docs/Web/API/Node/previousSibling

答案 1 :(得分:0)

的document.getElementById(&#34; someid&#34)。parentElement.previousElementSibling.textContent;

被修改

答案 2 :(得分:0)

let content = document.querySelectorAll('h3');

let count = content.length;

if (count) {

  for (let i = 0; i < count; i++) {
    alert(content[i].textContent);      
  }
}

https://jsfiddle.net/2kk49yLp/1/