遍历文本节点和元素节点

时间:2017-12-11 17:03:50

标签: javascript children nodechildren

我使用element.children遍历文本节点的元素节点和childNodes。 如何迭代文本节点和元素节点?

<div class="form-group">
  <%= label_tag :sex, 'Sex' %>
    <div class="btn-group" data-toggle="buttons">
      <label class="btn btn-default active">
        <%= radio_button_tag('options', 'male', params[:options] == 'male') %>
        Value1
      </label>
      <label class="btn btn-default">
        <%= radio_button_tag('options', 'Female', params[:options] == 'Female') %>
        Value2
      </label>
    </div>
  <% end %>
</div>

我可以使用childNodes访问元素吗?

1 个答案:

答案 0 :(得分:1)

只需使用包含元素和文本节点的childNodes

const childNodes = this.element.childNodes;
for (let i = 0; i < childNodes.length; i++) {
  if (childNodes[i].nodeType == 1) {
    // do something with childrenNodes[i] element
  } else if (childNodes[i].nodeType == 3) {
    // do something with childrenNodes[i] text node
  }
}

您应该通过nodeType区分它们,而不是nodeName区分它们。

相关问题