Kenji Crosland
Kenji Crosland

Reputation: 3034

Append several identical elements within a for loop

On a particular page, this markup appears several times:

<li class= "PRICE">
<label>Total Value:</label>
<span>$2,581</span>
</li>

I would like to change it to this dynamically using Javascript:

<li class= "PRICE">
<a href="mailto:[email protected]">Additional Savings</a>
</li>

While I can do this once, I'm having trouble changing all instances of this markup on the page, because I'm not sure how to create several instances of the same element:

var bottomSavings = document.getElementsByClassName("PRICE");
var newLink = document.createElement('a');
newLink.href = "mailto:[email protected]?";
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);
};

What happens is since there is only one "newLink" element, it can only append once. How do I make multiple and append to each?

Upvotes: 0

Views: 40

Answers (1)

samanime
samanime

Reputation: 26537

You need to create a newLink element for each item. The easiest way to do this is simply move the code that created your anchor element in to the loop too:

var bottomSavings = document.getElementsByClassName("PRICE");
for (var i = i=0;i<bottomSavings.length;i++) {
    var newLink = document.createElement('a');
    newLink.href = "mailto:[email protected]?";
    newLink.innerHTML = "Additional Savings";
    bottomSavings[i].removeChild(bottomSavings[i].children[0]);
    bottomSavings[i].removeChild(bottomSavings[i].children[0]);
    bottomSavings[i].appendChild(newLink);
};

Upvotes: 1

Related Questions