查找多个 HTML 元素的子元素并用作自定义属性的功能

问题描述 投票:0回答:2

因此,我有以下包含多个

<div>
元素的结构,我想在数据属性 (
data-children
) 中显示每个元素内的子元素。我希望它能够通过 JS 动态变化,而不是手动更改属性,这样当我添加/删除子元素时它就会发生变化。

<h2 class="amount_title" data-children="1">The amount of children of this element is </h2>

    <div class="parent_container">
        <div class="children_element">
            <div>
                <p>Lorem ipsum dolor sit amet.</p>
            </div>
            <button>Button</button>
        </div>
    </div>

<h2 class="amount_title" data-children="2">The amount of children of this element is </h2>

    <div class="parent_container">
        <div class="children_element">
            <div>
                <p>Lorem ipsum dolor sit amet.</p>
            </div>
            <button>Button</button>
        </div>
        <div class="children_element">
            <div>
                <p>Lorem ipsum dolor sit amet.</p>
            </div>
            <button>Button</button>
        </div>
    </div>

所以现在我正在执行以下操作来获取每个元素的子元素并填充每个标题的

data-attribute

const parentContainer = document.querySelectorAll('.parent_container')
const amountTitle = document.querySelectorAll('.amount_title')

let childrenAmount1 = parentContainer[0].childElementCount
amountTitle[0].dataset.children = childrenAmount1

let childrenAmount2 = parentContainer[1].childElementCount
amountTitle[1].dataset.children = childrenAmount2

我有一些这样的东西,所以显然不理想。哪个函数可以帮助我遍历所有这些元素并用每个元素的子元素数量相应地填充每个数据集?谢谢你。

我尝试执行 for () 循环,但所有数据集都从数组中的最后一项获取了子项的数量

javascript html dataset children custom-data-attribute
2个回答
1
投票

基于此配置,您的最佳策略是获取每个标题后的下一个元素。 虽然我建议使用包装器根据每个包装器内容设置标题

.wrapper > amount_title|parent_container
首先循环遍历所有包装器并从包装器引用中获取其子级

const titles = document.querySelectorAll(".amount_title");
titles.forEach((title) => {
  const next = title.nextElementSibling;
  if (!next.classList.contains("parent_container")) { return false; } // killswitch
  title.innerHTML = `The amount of children of this element is ${ next.childElementCount }`;
});
<h2 class="amount_title" data-children="1">The amount of children of this element is </h2>
<div class="parent_container">
    <div class="children_element">
        <div>
            <p>Lorem ipsum dolor sit amet.</p>
        </div>
        <button>Button</button>
    </div>
</div>

<h2 class="amount_title" data-children="2">The amount of children of this element is </h2>
<div class="parent_container">
    <div class="children_element">
        <div>
            <p>Lorem ipsum dolor sit amet.</p>
        </div>
        <button>Button</button>
    </div>
    <div class="children_element">
        <div>
            <p>Lorem ipsum dolor sit amet.</p>
        </div>
        <button>Button</button>
    </div>
</div>


编辑: 包装方法:

const wrappers = document.querySelectorAll(".wrapper");
wrappers.forEach((wrapper) => {
  const title = wrapper.querySelector(".amount_title");
  const contents = wrapper.querySelector(".parent_container");
  if (!title || !contents) { return; } // killswitch
  title.innerText = `The amount of children of this element is ${ contents.childElementCount }`
});
<div class="wrapper">
  <h2 class="amount_title" data-children="1">The amount of children of this element is </h2>
  <div class="parent_container">
      <div class="children_element">
          <div>
              <p>Lorem ipsum dolor sit amet.</p>
          </div>
          <button>Button</button>
      </div>
  </div>
</div>

<div class="wrapper">
  <h2 class="amount_title" data-children="2">The amount of children of this element is </h2>
  <div class="parent_container">
      <div class="children_element">
          <div>
              <p>Lorem ipsum dolor sit amet.</p>
          </div>
          <button>Button</button>
      </div>
      <div class="children_element">
          <div>
              <p>Lorem ipsum dolor sit amet.</p>
          </div>
          <button>Button</button>
      </div>
  </div>
</div>


0
投票

只需选择所有标题并使用

forEach
循环即可循环浏览所有这些标题。然后选择下一个兄弟并计算所有具有
child_element
类的元素:

window.addEventListener('DOMContentLoaded', getAmountTitles);

function getAmountTitles() {
  const HEADLINES = document.querySelectorAll('h2.amount_title');
  HEADLINES.forEach(headline => {
    let parent_container = headline.nextElementSibling;
    let amountChildElements = countChildrenElements(parent_container);
    headline.dataset.children = amountChildElements;
    
    headline.insertAdjacentText('beforeend', amountChildElements);
  });
}

function countChildrenElements(parentElement) {
  return (parentElement.querySelectorAll('.children_element').length);
}
  
<h2 class="amount_title">The amount of children of this element is </h2>

<div class="parent_container">
  <div class="children_element">
    <div>
      <p>Lorem ipsum dolor sit amet.</p>
    </div>
    <button>Button</button>
  </div>
</div>

<h2 class="amount_title">The amount of children of this element is </h2>

<div class="parent_container">
  <div class="children_element">
    <div>
      <p>Lorem ipsum dolor sit amet.</p>
    </div>
    <button>Button</button>
  </div>
  <div class="children_element">
    <div>
      <p>Lorem ipsum dolor sit amet.</p>
    </div>
    <button>Button</button>
  </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.