Reputation: 83
I need help to populate the text from each element of span and em into Attribute for each elements.
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>
Upvotes: 0
Views: 960
Reputation: 865
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);
});
Upvotes: 2