首页 > 解决方案 > Vanilla JS - 为所有元素设置属性

问题描述

我需要帮助将spanem的每个元素的文本填充到每个元素的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>

标签: javascript

解决方案


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/


推荐阅读