After changing parentNode.innerHTML, parentNode cannot be accessed

Let's say I have the following DOM structure and scripts

var test = document.getElementById('test');
test.parentNode.innerHTML += 'hello';
console.log(test.parentNode); // null
console.log(document.getElementById('test').parentNode); // normal result
<div>
<div id="test"></div>
</div>
Run code

As stated above, the script says that the first outputs null, while the second outputs the actual node, does anyone know why the first output nullis not a regular node?

+4
source share
5 answers

innerHTML . test , test id. test DOM . test document.getElementById('test') DOM Element.

createTextNode appendChild :

var test = document.getElementById('test');
test.parentNode.appendChild(document.createTextNode('hello'));
console.log(test.parentNode); 
+4

val + = b val = val + b. , .

, appendChild, innerhtml.

+2

:

  • DOM node 'test'
  • DOM node DOM node <div id="test"></div>Hello ( , ).
  • node DOM node, (! DOM!)
  • DOM node "test" ( , .
  • node ( )

DOM node 'test' - , . , test.innerHTML, , - , DOM node .

var test = document.getElementById('test');
test.parentNode.innerHTML += 'additional text';
console.log(test.parentNode); // null
console.log(test.innerHTML);
console.log(document.getElementById('test').parentNode); // normal result
<div>
<div id="test">Original text</div>
</div>
+2

:

test.parentNode.innerHTML += 'hello';

:

test.parentNode.innerHTML = test.parentNode.innerHTML + 'hello';

, + "hello". .

You can try

test.parentNode.appendChild(document.createTextNode('hello'));
+1
source

When adding html with test.parentNode.innerHTML += 'hello';(which is equal to test.parentNode.innerHTML = test.parentNode.innerHTML + 'hello';), it actually recreates the element, therefore test(which refers to the element) is no longer available in dom.

Instead, create a textNode using and add using that save other elements. createTextNode appendChild

var test = document.getElementById('test');
test.parentNode.appendChild(document.createTextNode('hello'));
console.log(test.parentNode);
console.log(document.getElementById('test').parentNode);
<div>
  <div id="test"></div>
</div>
Run code
0
source

Source: https://habr.com/ru/post/1648079/


All Articles