我需要帮助将 span 和 em 的每个元素中的文本填充到每个元素的“属性”中。
var spanTxt = document.querySelector("div a span").textContent;
var emTxt = document.querySelector("div a em").textContent;
var divAll = document.querySelectorAll("section a");
for(var i=0; i<divAll.length; i++){
divAll[i].setAttribute("list-span", spanTxt);
divAll[i].setAttribute("list-em", emTxt);
}
<section>
<div><a href="#">Line <span>Test 1</span> <em>One</em></a></div>
<div><a href="#">Line <span>Test 2</span> <em>Two</em></a></div>
</section>
答案 0 :(得分:1)
const linksArray = Array.from(document.querySelectorAll('section a')); // we use Array.from to transform the NodeList from querySelectorAll to an array. Needs to IE11
linksArray.forEach(linkEl => { // we search for every span and em inside the link
linkEl.setAttribute("list-span", linkEl.querySelector('span').textContent);
linkEl.setAttribute("list-em", linkEl.querySelector('em').textContent);
});