在特定页面上,此标记会多次出现:
<li class= "PRICE">
<label>Total Value:</label>
<span>$2,581</span>
</li>
我想使用Javascript动态地将其更改为:
<li class= "PRICE">
<a href="mailto:example@example.com">Additional Savings</a>
</li>
虽然我可以执行此操作,但我无法在页面上更改此标记的所有实例,因为我不确定如何创建相同元素的多个实例:
var bottomSavings = document.getElementsByClassName("PRICE");
var newLink = document.createElement('a');
newLink.href = "mailto:example@example.com?";
newLink.innerHTML = "Additional Savings";
for (var i = i=0;i<bottomSavings.length;i++) {
bottomSavings[i].removeChild(bottomSavings[i].children[0]);
bottomSavings[i].removeChild(bottomSavings[i].children[0]);
bottomSavings[i].appendChild(newLink);
};
因为只有一个&#34; newLink&#34;会发生什么?元素,它只能追加一次。如何制作多个并附加到每个?
答案 0 :(得分:1)
您需要为每个项目创建一个newLink
元素。最简单的方法是将创建锚元素的代码移动到循环中:
var bottomSavings = document.getElementsByClassName("PRICE");
for (var i = i=0;i<bottomSavings.length;i++) {
var newLink = document.createElement('a');
newLink.href = "mailto:example@example.com?";
newLink.innerHTML = "Additional Savings";
bottomSavings[i].removeChild(bottomSavings[i].children[0]);
bottomSavings[i].removeChild(bottomSavings[i].children[0]);
bottomSavings[i].appendChild(newLink);
};