在几个标签之间获取文本

时间:2016-08-11 10:25:05

标签: javascript regex

我在页面上有这个HTML代码:

<div style="display:none" id="roles">
        <span>Manager</span>
        <span>Seller</span>
</div>

我想在spans元素之间获取字符串数组。

var roles = document.getElementById("roles").innerText.match("what i should get here"); // output roles = ["Manager", "Seller"]

6 个答案:

答案 0 :(得分:6)

var roles = Array.prototype.slice.call(document.getElementById('roles').getElementsByTagName('span')).map(function(node) {
  return node.innerText || node.textContent;
});

console.log(roles);
<div style="display:none" id="roles">
  <span>Manager</span>
  <span>Seller</span>
</div>

答案 1 :(得分:4)

您需要迭代span元素并获取其文本。

//Get the span elements
var spans = document.querySelectorAll("#roles span");
var roles = [];

//Iterate the elements
for (var i = 0; i < spans.length; i++) {
  //fetch textContent and push it to array
  roles.push(spans[i].textContent);
}

console.log(roles)
<div style="display:none" id="roles">
  <span>Manager</span>
  <span>Seller</span>
</div>

您也可以按@Tushar

的建议使用

//Get the span elements
var spans = document.querySelectorAll("#roles span");
var roles = Array.from(spans).map(s => s.textContent);
console.log(roles)
<div style="display:none" id="roles">
  <span>Manager</span>
  <span>Seller</span>
</div>

答案 2 :(得分:3)

使用 querySelectorAll 获取所有span元素,然后借助 Array.from 方法将其转换为数组(旧浏览器使用[].slice.call )现在使用 Array#map 方法生成结果数组。

// for older browser use `[].slice.call(...` instead of `Array.from(...`
var res = Array.from(document.querySelectorAll('#roles span')).map(function(e) {
  return e.textContent;
});

console.log(res);
<div style="display:none" id="roles">
  <span>Manager</span>
  <span>Seller</span>
</div>

答案 3 :(得分:0)

<div id="exmpl1">   
<span id="1st"> A1</span>
<span id="2nd"> A2</span>
<span id="3rd"> B1</span>
<span id="4th"> B2</span>
<span id="5th"> C1</span>
</div>

var spans = document.getElementById('exmpl1').getElementsByTagName('span'),
obj = {};

for (var i = 0, j = spans.length; i < j; i++) {
    obj[spans[i].id] = spans[i].textContent || spans[i].innerText;
}

console.log(obj);

答案 4 :(得分:0)

我建议首先找到角色div的后代,然后在for循环中迭代它们,将结果发布到数组中。

    //Define the parent div
    var parent = document.getElementById('roles');

    //Find the children of the parent div
    var children = parent.getElementsByTagName('span');

    //Count how many children there are within the parent div
    var totalChildren = children.length;

    //Declare a new array to store the roles in
    var rolesArray = [];

    //And let the for loop push each role into the array
     for (var i = 0; i < totalChildren; i++) {
        rolesArray.push(children[i].innerText);
     }

答案 5 :(得分:0)

这是另一种解决方案:

var spans;  
document.querySelectorAll('#roles > span').forEach(function(element){
        spans.push(element.textContent);
 });