首页 > 解决方案 > 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>

标签: javascript

解决方案


将属性设置为元素使用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>


推荐阅读