What is the correct way to overwrite the text in an anchor element without losing the stored icon?
My current solution changes the text value, but the icon next to it is lost.
This is the element (assembled button):
<a id="btn_lang" class="lang_btn"> <i class="fa fa-commenting-o"></i> Verfügbare Sprachen und Länder</a>
This is the icon-library i am using:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
Following actions get performed, by pushing a button (my approach for changing the text):
<script>
function AT(){
document.getElementById("btn_lang").innerHTML = "changed value";
}
</script>
Appearance before pushing the button:
Appearance after pushing the button (-> text gets changed, but icon is missing):
If the complete HTML / CSS script is necessary, I can submit it later (I have reduced it to the code lines listed for better clarity).
Do I have to define the icon again when using .innerHTML?
2
Answers
Problem is you are setting the whole
#btn_lang
to your new HTML.Instead you could just change the html of
#btn_lang > span
, else you’d have to define the icon (<i>
), as you already said, again.Here’s an example:
If you don’t want to have an ID on your span you can simply do this:
Hope this helps!
Adding an extra element as suggested in this answer is certainly the easiest way to go and a very readable option, but if for whatever reason you couldn’t add an extra tag, then you can still do what you want.
Aside from HTML tags, all bare blocks of text in a HTML DOM document are
TextNode
elements. If you get all nodes in the button, find theTextNode
you need and then edit its text, the existing HTML (the<i>
) is not affected.