简体   繁体   English

Vanilla JS - 将属性设置为所有元素

[英]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.我需要帮助将来自spanem 的每个元素的文本填充到每个元素的 Attribute 中。

Expected Results预期成绩在此处输入图片说明

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

http://jsfiddle.net/7v3womnt/ http://jsfiddle.net/7v3womnt/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在香草JS中将参数放入setAttribute函数 - How to put arguments onto setAttribute function in vanilla JS Vanilla JS:查找仅包含文本的所有DOM元素 - Vanilla JS: Find all the DOM elements that just contain text Vanilla JS - 可以在子元素上添加/删除类,但所有类都处于活动状态 - Vanilla JS - Can add/remove class on child elements but all are active Vanilla JS:HTML 在单击事件侦听器中执行所有 JS 工作后正在获取元素 - Vanilla JS: HTML Elements are being fetched after executing all JS work in click event listener Vanilla JS除了&#39;active&#39;类之外的所有其他元素都删除了类 - Vanilla JS remove class from all other elements besides 'active' class 使用 Vanilla JS 查找和替换具有特定颜色的所有元素的最佳方法是什么? - What is the best way to find and replace all elements with a certain colour using Vanilla JS? Vanilla JS:根据光标位置选择父类中具有类的所有元素 - Vanilla JS: Select all elements with class within parent based on cursor position Plain Vanilla JavaScript - 重置所有元素的外观 - Plain Vanilla JavaScript - Reset appearance of all elements 带有子元素的链接上的 Vanilla JS 目标 href - Vanilla JS target href on link with child elements 在vanilla JS中定位下一个兄弟元素的父元素 - Targeting parents elements next sibling in vanilla JS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM