imanoob
imanoob

Reputation: 47

How can I change innerHtml without affecting a tag that is in it?

this is the inner html I wish to change (1.1k):

<a id="js-fb-1" href=""><i class="fa fa-facebook" aria-hidden="true"></i> 1.1k</a>

This is my js code:

document.getElementById("js-fb-1").innerHTML = string;

However, it removes the i tag that is also within the anchor tag. I have tried

document.getElementById("js-fb-1").innerHTML = "<i class="fa fa-facebook" aria-hidden="true"></i>"+ string

but it doesn't work. How can I keep the i tag and only change the number?

Thanks in advance

Upvotes: 1

Views: 2158

Answers (3)

SuperDJ
SuperDJ

Reputation: 7661

First get the inner html than add what you want inside of the outer html

let a = document.getElementById("js-fb-1");
let inner = a.innerHTML;
inner = inner.replace(a.text, 'example'); // removes text but keeps the html
a.innerHTML = inner;

console.log(inner);
<a id="js-fb-1" href=""><i class="fa fa-facebook" aria-hidden="true"></i> 1.1k</a>

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Template_literals

Upvotes: 0

Scott Marcus
Scott Marcus

Reputation: 65853

All content in HTML is generically known as a "node" and all nodes have a nodeType, which is a number defining what kind of content it is. Text nodes are 3, so if you loop over all the childNodes of the <a> and look for a nodeType of 3, you've found raw text and can change its .textContent, not .innerHTML (which should be avoided when possible due to its security and performance issues).

// Get a collection of all the child nodes in the <a>
// Nodes can be elements, attributes, raw text, comments, etc.
let nodes = document.querySelector("a").childNodes;

for(var i = 0; i < nodes.length; i++){
  // Check for a text node
  if(nodes[i].nodeType === 3){
    nodes[i].textContent = "Something new";
  }
};

console.log(document.querySelector("a").outerHTML);
<a id="js-fb-1" href=""><i class="fa fa-facebook" aria-hidden="true"></i> 1.1k</a>

Upvotes: 3

Barmar
Barmar

Reputation: 782584

It's best to add a span around the text that you want to be able to replace. Than you can select that nested element and replace its contents, without disturbing everything around it.

let string = "2.3k";
document.querySelector("#js-fb-1 span").innerText = string;
<a id="js-fb-1" href=""><i class="fa fa-facebook" aria-hidden="true"></i> <span>1.1k</span></a>

Upvotes: 0

Related Questions