smo*_*tru 4 javascript getelementsbytagname
我需要创建一个数组,其中包含没有 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>
Run Code Online (Sandbox Code Playgroud)
这是我想得到的
text[1] = "Hello world!";
text[2] = "Hello!";
text[3] = "What are you doing?";
text[4] = "Fine, and you?";
text[5] = "Thank you!";
Run Code Online (Sandbox Code Playgroud)
这是我尝试过但在我的浏览器中似乎无法正常工作的内容:
var elements = document.getElementsByTagName('*');
console.log(elements);
Run Code Online (Sandbox Code Playgroud)
附注。我需要使用 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);
}
}
Run Code Online (Sandbox Code Playgroud)
你可以做这样的事情
结果 = ["What are you doing?", "Fine, and you?"]
或者你可以使用 document.documentElement.getElementsByTagName('*');
还要确保你的代码在这个里面
document.addEventListener('DOMContentLoaded', function(){
/// Code...
});
Run Code Online (Sandbox Code Playgroud)
如果这只是你需要的标题,你也可以这样做
array.push(document.title);
Run Code Online (Sandbox Code Playgroud)
通过脚本和样式保存循环