I1:N2
var el = document.getElementById("parentDiv");
console.log(el.textContent);
console.log(el.innerText);
console.log(el.innerHTML);
运行此命令时,它始终返回'parent div'以及子元素中的所有文本。有没有办法只使用js返回'父div'?
答案 0 :(得分:5)
遍历所有子节点,跳过任何非文本节点,从中获取文本。
var el = document.getElementById("parentDiv");
var text = "";
for (let i = 0; i < el.childNodes.length; i++) {
let node = el.childNodes[i];
if (node.nodeType === Node.TEXT_NODE) {
text += node.data;
}
}
console.log(text);
&#13;
<div id="parentDiv">
parent div
<p>p</p>
<div>
this text is in a div
<span>span</span>
<a>im a link!</a>
<div>
another div
<div>
<span><a>link in a span</a></span>
</div>
</div>
</div>
</div>
&#13;
答案 1 :(得分:2)
最简单的方法之一是克隆父级,从克隆中删除非TEXT-NODE子级,然后获取文本:
const element = document.getElementById('parent');
const clone = element.cloneNode(true); // use deep
Array.prototype.slice.call(clone.children).forEach(child => {
child.nodeType !== Node.TEXT_NODE && clone.removeChild(child);
});
const result = clone.innerHTML;
console.log(result);
<div id="parent">
PARENT
<div>A</div>
<div>B</div>
<div>C</div>
</div>