Home > other >  difference between .textContent and .firstChild.data
difference between .textContent and .firstChild.data

Time:02-03

assuming I have a html, with an h2, what's the difference between

document.querySelector('h2').textContent = 'abcdefg';
<h2>
</h2>

and

document.querySelector('h2').firstChild.data = 'abcdefg';
<h2>
</h2>

?

I'm mainly interested in knowing what this .data is, I didn't find the documentation for it

CodePudding user response:

The first one will always work to set the text content of the element in question.

The second will only work if the element's first child is a text node (aka CharacterData).

For example, using .data has no observable change if the first-child is an Element.

document.querySelector('#no-text-children').firstChild.data = 'abcdefg';
document.querySelector('#only-text-children').firstChild.data = 'abcdefg';
<h2 id="no-text-children"><span>this is the span content</span></h2>
<h2 id="only-text-children">this is the h2 content</h2>

Using .textContent does not suffer from any such limitations

document.querySelector('#no-text-children').textContent = 'abcdefg';
document.querySelector('#only-text-children').textContent = 'abcdefg';
<h2 id="no-text-children"><span>this is the span content</span></h2>
<h2 id="only-text-children">this is the h2 content</h2>

  • Related