Reputation: 1342
I have a nested <a>
element that I want to change the text and attributes for.
So far I am getting the a tag and setting the innerHtml to something else. However I feel this might be bad practise.
Heres the code I need to target and change
<li class="promo-bar">
<div>
<span class="icon-with-text">
// I want to change this a element
<a href="mywebsite.com" data-di-id="1">Free delivery</a>
</span>
</div>
</li>
This what I have tried so far that does work. However I feel that either using innerHtml
may be bad practise or that there is a cleaner way that is more descriptive.
var newLink = document
.querySelector(".promo-bar ")
.children[0].querySelector("a");
var myNewLinkHtml = `
<a
class="newClassName"
href="#"
id="new-id"
>Why choose us?</a
>
`;
newLink = newLink.innerHTML = myNewLinkHtml;
I would like to get the <a>
element and change the text and have the ability to add class names and custom attributes.
If using innerHtml is ok then great, else my aim is to use only Vanilla Javascript methods to achieve this.
Upvotes: 1
Views: 190
Reputation: 7315
If you want to use ready html instead of editing the text and each property your best bet is to place that html in a temporary element and then replace the original link with the one(s) created in the temporary element.
var newLink = document.querySelector(".promo-bar>:first-child a");
// `document.querySelector(".promo-bar a")` would probably work as well, but I don't know what your whole html looks like and used `.children[0]`
var temp = document.createElement("div");
temp.innerHTML = `<a class="newClassName" href="#" id="new-id">Why choose us?</a>`;
// using while is safer in case more than 1 nodes are added using `innerHTML = "..."`
while (temp.childNodes.length) newLink.parentElement.insertBefore(temp.firstChild, newLink);
newLink.remove();
<li class="promo-bar">
<div>
<span class="icon-with-text">
// I want to change this a element
<a href="mywebsite.com" data-di-id="1">Free delivery</a>
</span>
</div>
</li>
General tip about innerHTML
: try to avoid altering the innerHTML
of the main dom tree as it could remove event listeners and change references to dom objects.
Upvotes: 1
Reputation: 2705
You can access each property independently and update them as you need.
For the content use textContent.
To add classes, classList.add().
The id
can be updated assigning a new one.
const el = document.querySelector('.promo-bar a');
el.id = 'new-id';
el.classList.add('new-class');
el.textContent = 'New content';
<li class="promo-bar">
<div>
<span class="icon-with-text">
// I want to change this a element
<a href="mywebsite.com" data-di-id="1">Free delivery</a>
</span>
</div>
</li>
Upvotes: 2