如何从包含子项的div中获取文本

时间:2017-05-14 18:45:01

标签: javascript children nodevalue child-nodes

我目前正在学习JavaScript,我遇到以下问题。是否有可能只从包含子项的div中获取文本?我设法让它只适用于div的孩子们面前的文字。

PS:我想提一下,我正在尝试使用纯JavaScript实现这一目标。



var Class = document.querySelectorAll('div,b');
for (var i=0; i < Class.length; i++){
   console.log(Class[i].childNodes[0].nodeValue);
}
&#13;
<div class="Bio">
My name is <b>John Doe</b> and I am coming from Texas
</div>

<div class="Bio">
My name is <b>Jean Frye</b> and I am coming from Alabama
</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:3)

这不是很干净的方式,但尝试这样的事情:

&#13;
&#13;
//get all div's with Bio css class (You can change it)
var Class = document.querySelectorAll('.Bio');
var sp=document.getElementById('res');
var arr=[]; //I put result into array so You can use it where You need
for (var i=0; i < Class.length; i++) {
   for(var x=0;x<Class[i].childNodes.length;x++) {
     if(Class[i].childNodes[x].nodeValue==null) {
        //get value, innerHTML, from <b>
   			//res.innerHTML+=Class[i].childNodes[x].innerHTML+'<br>';
        arr.push(Class[i].childNodes[x].innerHTML);
        } else {
        //get div innerHTML (before,after every child node
        //res.innerHTML+=Class[i].childNodes[x].nodeValue+'<br>';
        arr.push(Class[i].childNodes[x].nodeValue);
        }
   }
}
//show result into that span
for(var i=0;i<arr.length;i++) {
res.innerHTML+=arr[i]+'<br>';
}
&#13;
<div class="Bio">
My name is <b>John Doe</b> and I am coming from Texas
</div>

<div class="Bio">
My name is <b>Jean Frye</b> and I am coming from Alabama
</div>
<br><br>
<!-- I use this span to show result -->
<span id="res"></span>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

var Class = document.querySelectorAll('div');

for (var i=0; i < Class.length; i++){
   var children = [];
   var boldText = Class[i].querySelectorAll('b')[0].innerText;
   var otherText = Class[i].innerText.split(Class[i].querySelectorAll('b')[0].innerText)

   children.push(otherText[0]);
   children.push(boldText);
   children.push(otherText[1]);

   console.log(children);
}

输出: -

  

[&#34;我的名字是&#34;,&#34; John Doe&#34;,&#34;我来自德克萨斯州&#34;]

     

[&#34;我的名字是&#34;,&#34; Jean Frye&#34;,&#34;我来自阿拉巴马州&#34;]

这可能会成功。

答案 2 :(得分:1)

您可以使用innerText仅获取所选元素的文字。

var Class = document.querySelectorAll('div');
for (var i=0; i < Class.length; i++){
   console.log(Class[i].innerText);
}
<div class="Bio">
My name is <b>John Doe</b> and I am coming from Texas
</div>

<div class="Bio">
My name is <b>Jean Frye</b> and I am coming from Alabama
</div>

有关详情,请参阅MDN article on innerText