香草JS-所有元素的SetAttribute

时间:2020-11-04 01:46:16

标签: javascript

我需要帮助将 span em 的每个元素中的文本填充到每个元素的“属性”中。

预期结果 enter image description here

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>

1 个答案:

答案 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);
});

http://jsfiddle.net/7v3womnt/