我需要创建一个数组,其中包含一个页面中的所有文本,而不使用 jQuery。这是我的 HTML:
<html>
<head>
<title>Hello world!</title>
</head>
<body>
<h1>Hello!</h1>
<p>
<div>What are you doing?</div>
<div>Fine, and you?</div>
</p>
<a href="http://google.com">Thank you!</a>
</body>
</html>
这是我想要的
text[1] = "Hello world!";
text[2] = "Hello!";
text[3] = "What are you doing?";
text[4] = "Fine, and you?";
text[5] = "Thank you!";
这是我尝试过但在我的浏览器中似乎无法正常工作的方法:
var elements = document.getElementsByTagName('*');
console.log(elements);
附言。我需要使用 document.getElementsByTagName('*');并排除“脚本”和“样式”。
最佳答案
var array = [];
var elements = document.body.getElementsByTagName("*");
for(var i = 0; i < elements.length; i++) {
var current = elements[i];
if(current.children.length === 0 && current.textContent.replace(/ |\n/g,'') !== '') {
// Check the element has no children && that it is not empty
array.push(current.textContent);
}
}
你可以这样做
result = ["你在做什么?", "很好,你呢?"]
或者您可以使用 document.documentElement.getElementsByTagName('*');
还要确保你的代码在这个里面
document.addEventListener('DOMContentLoaded', function(){
/// Code...
});
如果只是你需要的标题,你也可以这样做
array.push(document.title);
保存脚本和样式的循环
关于javascript - 如何从一个数组中的所有标签中获取所有文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17727977/