如何使用.textContent从所选div中获取不包含其子文本的文本

时间:2016-03-01 22:23:13

标签: javascript

我正在使用以下代码尝试打印出传递给函数的div的textContent。我只想要选择的div文本,而不是它的孩子们。

我见过几个例子,但都使用了我不想要的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>
&#13;
&#13;
&#13;

提前致谢

4 个答案:

答案 0 :(得分:1)

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;
}

答案 1 :(得分:1)

您可以抓住第一个元素childNodes,这将是有问题的text node。请注意,文本节点对空白区域很敏感。

&#13;
&#13;
function changeText (element) {
  var thisEl = document.getElementById(element);

  console.log(thisEl.childNodes[0].nodeValue);

}

changeText('container');
&#13;
<div id='container'>
  this is a test 1
  <div>
    this is a test 2
    <div>
      this is a test 3
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您是否只需要所选文字? https://github.com/timdown/rangy但您也可以获得所选文字的外部元素。

答案 3 :(得分:0)

使用.textContentchildNodes[0]

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;