我希望将html页面中的所有文本都转换为字符串,然后在控制台上打印它。到目前为止,我有一段代码只能部分工作,因为document.body.innerText返回文本和线制动器,我当然不想要。我希望我的所有文字都出现在一行
中<html>
<head>
<h1>wtf</h1>
</head>
<body>
<div>dddiiiv</div>
<a>aaaaa</a>
<p>ppp</p>
<div>div</div>
<div id="impar"></div>
<div id="par"></div>
<div id="all"></div>
<script>
var elems = document.body.innerText;
var odd = "";
var even = "";
var all = "";
for (k in elems){
all = all + elems[k];
if (k % 2 === 0) {
even = even + elems[k]
} else {
odd = odd + elems[k]
}
}
console.log(all);
console.log(odd);
console.log(even);
</script>
</body>
</html>
有什么想要绕过内部文本的刹车?
答案 0 :(得分:1)
我使用.trim()和codepen URL作为参考 - http://codepen.io/nagasai/pen/jrPpeK
<html>
<head>
<h1>wtf</h1>
</head>
<body>
<div>dddiiiv</div>
<a>aaaaa</a>
<p>ppp</p>
<div>div</div>
<div id="impar"></div>
<div id="par"></div>
<div id="all"></div>
</body>
</html>
的Javascript
var elems = document.body.innerText;
var odd = "";
var even = "";
var all = "";
for (k in elems){
all = all + elems[k];
if (k % 2 === 0) {
even = (even + elems[k]).trim();
} else {
odd = (odd + elems[k]).trim();
}
}
console.log(all);
console.log(odd);
console.log(even);
希望这是有帮助的