I am trying to add some text to an existing element using textContent
. But when I use =
(addition assignment) operator but in the result, already existing tags like b
has lost its effect. I think I am just adding to it, but it also has effect in the previous content. Can anyone explain why? I checked the docs but didn't find anything about this.
HTML:
<div id="divA">Something<b>bold</b></div>
JS
const some = document.getElementById("divA");
some.textContent = "Hi"; // This results in : "Something boldHi" without the bolded formatting.
some.textContent = some.textContent "Hi"; //This too results in the same!
Thanks in advance!
CodePudding user response:
The .textContent
value of an element returns just that - the text content, which is plain text, not the HTML markup of the contents.
If you do
some.textContent = "Hi"
The text content of the container will be retrieved, which will not contain any tags - eg
<div id="divA">Something<b>bold</b></div>
will retrieve:
Something bold
Concatenating onto that and then assigning the result back to the .textContent
of the element results in the element's descendants replaced with a single text node, where the text node's value is the value assigned.
If you use .innerHTML =
instead, the prior HTML markup of the descendants will be preserved - but the descendants will all be re-parsed according to the HTML markup assigned, so event listeners and related things that depend on DOM elements will be lost. A better option is to use .insertAdjacentHTML
, which does not require re-parsing of the descendants.
An even better option would be to append a node itself instead of trying to write HTML markup (which is potentially unsafe), eg
some.appendChild(document.createTextNode('Hi'))
CodePudding user response:
When you are taking the textContent
then you will get Somethingbold
which is just plain text wihtout HTML tags
console.log(some.textContent); // Somethingbold
You are appending the textContent
, instead you shold use innerHTML
const some = document.getElementById("divA");
some.innerHTML = "Hi"; // This results in : "Something boldHi" without the bolded formatting.
some.innerHTML = some.innerHTML "Hi"; //This too results in the same!
<div id="divA">Something<b>bold</b></div>