我正在尝试使用js获取我的html页面中所有h标签的文本内容。
但是当特定的h标签不存在时,我的代码停止工作。如果h标记未退出,我无法成功编写if语句测试。

我的html:

<h1> <a href="" >just a link </a>HTML testing File</h1>
<h2>Another text</h2>
<h4>An h4 text</h4>

我的js:
window.onload = word;
function word () {

var h=["h1","h2","h3","h4","h5","h6"];
var headings = [];
for (var i =0; i<h.length ;i++)
{


    if (document.getElementsByTagName(h[i]))
{
    headings[i] = document.querySelector(h[i]).textContent;
  alert(headings[i] );

}
else

{ alert(h[i]+"doesn't exist");
    }

}

}

任何帮助

最佳答案

如果条件用于验证heading[i],则应用。像这样

if(headings[i]){
      console.log(headings[i].textContent);
      }

window.onload = word;

function word() {
  var h = ["h1", "h2", "h3", "h4", "h5", "h6"];
  var headings = [];
  for (var i = 0; i < h.length; i++) {
    if (document.getElementsByTagName(h[i])) {
      headings[i] = document.querySelector(h[i]);
      if (headings[i]) {
        console.log(headings[i].textContent);
      }
    } else {
      alert(h[i] + "doesn't exist");
    }
  }
}
<h1> <a href="">just a link </a>HTML testing File</h1>
<h2>Another text</h2>
<h4>An h4 text</h4>

关于javascript - 如何使用js获取所有标题标签值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43950084/

10-11 12:50
查看更多