[英]How do I get the text from the selected div not including its childrens text using .textContent
我正在使用以下代码尝试并打印出传递给该函数的div的textContent。 我只想要选定的divs文本,也不要它的子元素。
我看到了一些示例,但是都使用了我不想要的jquery :)
function changeText(element){ var thisEl = document.getElementById(element); console.log(thisEl.textContent) } changeText('container')
<div id = 'container'> this is a test 1 <div> this is a test 2 <div> this is a test 3 </div> </div> </div>
提前致谢
function changeText(elementId) {
var childs = [].slice.call(document.getElementById(elementId).childNodes);
var text = '';
childs.forEach(function (child) {
if (child.nodeType === 3) {
text += child.nodeValue || '';
}
});
return text;
}
您可以获取元素的第一个childNodes
,这将是有问题的文本节点 。 请注意,文本节点对空白敏感。
function changeText (element) { var thisEl = document.getElementById(element); console.log(thisEl.childNodes[0].nodeValue); } changeText('container');
<div id='container'> this is a test 1 <div> this is a test 2 <div> this is a test 3 </div> </div> </div>
您只需要选择的文字吗? https://github.com/timdown/rangy但您也可以获取所选文本的外部元素。
使用.textContent
和childNodes[0]
<!DOCTYPE html> <html> <head> </head> <body> <div id='container'> this is a test 1 <div> this is a test 2 <div> this is a test 3 </div> </div> </div> <br> <br> <br> <br> <br> <output id="out"></output> <script> var tgt = document.getElementById("container").childNodes[0].textContent document.getElementById("out").innerHTML = tgt; </script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.