2

我目前正在学习 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);
}
<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>

4

3 回答 3

3

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

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

于 2017-05-14T19:18:03.620 回答
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);
}

输出 :-

[“我的名字是”、“John Doe”、“我来自德克萨斯”]

[“我的名字是”、“Jean Frye”、“我来自阿拉巴马州”]

这可能会奏效。

于 2017-05-14T19:09:57.933 回答
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>

有关详细信息,请参阅关于 innerText 的 MDN 文章

于 2017-05-14T18:51:31.107 回答