如何操作Dom只选择标签内的文本内容?

时间:2018-10-19 06:51:04

标签: javascript html

如何选择标签内的文本(不包括其他标签的内容)。例如:

<div id='id'>text that I want to select<p>text that I don't want</p></div>

在这种情况下,如何使用类似的方法来获取纯文本?

document.getElementByID('id').innerText

4 个答案:

答案 0 :(得分:4)

为此,您将遍历元素中的文本节点,而忽略非文本节点(包括子元素):

var element = document.getElementById("id");
var text = "";
for (var child = element.firstChild;
     child;
     child = child.nextSibling) {
  if (child.nodeType === Node.TEXT_NODE) {
    text += child.nodeValue;
  }
}

console.log(text);
<div id='id'>text that I want to select<p>text that I don't want</p></div>

答案 1 :(得分:0)

您还可以使用XPATH来选择元素自己的文本

Service
var result = document.evaluate( "//div[@id='id']/text()", document, null, XPathResult.STRING_TYPE, null );

alert(result.stringValue)

答案 2 :(得分:-1)

类似的东西可以做

 var t =
(document.getElementById("id") ).childNodes

for (let index = 0; index < t.length; index++) {
    const element = t[index];

   
    
    if( element.tagName === undefined ){  document.getElementById("out").append(element.cloneNode()) ;}

}
<div id='id'>text that I want to select<p>text that I don't want</p></div>

<div id="out" style="color:blue"></div>

答案 3 :(得分:-1)

console.clear()

function noChildTextContent(el) {
  var clone = el.cloneNode(true);
  var childNodes = clone.childNodes;
  var ret = "";
  for (let childNode in childNodes) {
    if (childNodes.hasOwnProperty(childNode)) {
      if (childNodes[childNode].nodeType == 3) {
        ret += ` ${childNodes[childNode].textContent}`
      }
    }
  }
  return ret.trim();
}
console.log(noChildTextContent(document.getElementById('id')))
<div id='id'>text that I want to select<p>text that I don't want</p>Want it again</div>