javascript - Vanilla JS - 为所有元素设置属性
问题描述
我需要帮助将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);
});
推荐阅读
- visual-studio-code - 如何注册调用函数的 VS Code 任务
- c# - Using loop to create multiple dropdownlistfor using different lists
- expression - 尝试根据表值从表中生成表达式
- javascript - JS 脚本仅适用于平板电脑/手机
- excel - 如何修复宏在#value之后仍然继续
- c# - Mimic linux openssl command in C#
- android - How does the step-counter from the samsung health app, count the steps?
- c# - ASP.NET Core 2.2 - Simple DB Query Question
- angular - 为什么 Angular 会删除内联标签之间的空格?
- firebase - 我想在firebase中存储限时数据