[英]Vanilla JS - SetAttribute to All Elements
I need help to populate the text from each element of span and em into Attribute for each elements.我需要帮助将来自span和em 的每个元素的文本填充到每个元素的 Attribute 中。
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>
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.