javascript - setAttribute 并更改文本
问题描述
如何使用 JavaScript 一次设置多个属性?
我有两个目标。
1-将*号更改为#(完成)
2-将属性设置为元素,但我不能
我想要这样
<div attributeForFuture># A</div>
<div><div attributeForFuture># B</div></div>
<div attributeForFuture># AA</div>
<div><div><div attributeForFuture># C</div></div></div>
let all = document.querySelectorAll("div");
for (newChanges of all) {
let r = newChanges.textContent.replace('*', '#');
newChanges.innerText = r;
}
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<div>* A</div>
<div><div>* B</div></div>
<div>* AA</div>
<div><div><div>* C</div></div></div>
</body>
</html>
解决方案
将属性设置为元素使用setAttribute()
javascript 的功能。但是对于替换,您必须对所有元素进行反向排序。所以反转所有元素的列表会先改变子元素再改变父元素
并且还使用innerHTML
而不是innerText
替换。
let all = document.querySelectorAll("div");
// need to reverse sort otherwise it will set Attribute to parents element.
all = [...all].sort((a, b) => (a > b ? 1 : -1))
for (newChanges of all){
var oldtext = newChanges.innerHTML; // store old text for check if replce or not
let r = oldtext.replace('*', '#');
if(oldtext != r){ // replace if it content what you find.
newChanges.innerHTML = r;
// use can set Attribute as follow.
newChanges.setAttribute('attributeForFuture', '');
}
}
console.log(document.querySelectorAll("section")[0].innerHTML)
<section>
<div>* A</div>
<div><div>* B</div></div>
<div>* AA</div>
<div><div><div>* C</div></div></div>
</section>
推荐阅读
- c - C 内存故障中的共享内存
- gnuplot - Gnuplot:如何从扁平表中绘制条形图
- visual-studio-2017 - VS Community 2017 - 使用会员/用户登录创建网站
- oracle - 在每个表修改日期的日期之间从不同表中获取数据
- java - 在 Android 模块中获取 WiFi SSID
- javascript - 如何使用带有循环功能的cheerio 传递新选项
- clojure - Clojure,如何将正确的参数传递给函数
- excel - Excel - 创建指向同名工作表的超链接
- python - 如何使用 iTune 的 API 下载文件并使用 python 导入字符串?
- javascript - DataTable JS 无法过滤小数列