根据父ID获取JS中的div数组

时间:2018-01-10 00:35:44

标签: javascript html

我有一个包含3列的页面。在每一列中都有几个具有相同类名的div,如此。

<div id="column1">
  <div class="child"></div>
  <div class="child"></div> 
  <div class="child"></div>  
</div>

<div id="column2">
  <div class="child"></div>
  <div class="child"></div> 
  <div class="child"></div>  
</div>

<div id="column3">
  <div class="child"></div>
  <div class="child"></div> 
  <div class="child"></div>  
</div>

我希望能够抓住每列下的每个子div并将它们存储到JS中的3个独立数组中。所以在伪代码中

var children1 = all children of #column1 with the class .child,
children 2 = all children of #column2 with the class .child,
children 2 = all children of #column2 with the class .child;

我需要能够根据它们所在的列将背景颜色应用于.child div。我将如何进行此操作?

2 个答案:

答案 0 :(得分:1)

使用document.querySelectorAll()返回NodeList个对象和Array.from()

实施例

&#13;
&#13;
var children1 = document.querySelectorAll('#column1 > .child'),
  children2 = document.querySelectorAll('#column2 > .child'),
  children3 = document.querySelectorAll('#column3 > .child'),
  content1 = Array.from(children1, child => child.textContent);

console.log(content1);
&#13;
<div id="column1">
  <div class="child">Column 1a</div>
  <div class="child">Column 1b</div>
  <div class="child">Column 1c</div>
</div>

<div id="column2">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

<div id="column3">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以选择以下

Imports System
Imports System.Text.RegularExpressions

    Sub RegexpSplitTxt()
        Dim pattern As String = "(\d{3}-[A-Z]{2}-\d{4})[A-Z]?(\/[A-Z])?(\/[A-Z])?"
        Dim replacement As String = "$2"
        Dim input As String = "100-AA-1001A/B/C"
        Dim result As String = Regexp ($1 Somewhere) & Regex.Replace(input, pattern, replacement)
        Console.WriteLine(result)
    End Sub