简体   繁体   中英

Why is child node missing from the parent node before removeChild?

why is the child node mssing inside the parent node prior to removal??

console.log(e); // logs the e element
console.log(e.parentNode); // logs the parent element but without element e inside
e.parentNode.removeChild(e);

When you log a DOM element, you are logging the JavaScript object representation of the element. The console will generally display ... between the opening and closing tags to represent that there is some content, but it doesn't mean that your child element doesn't exist.

If you want to see its contents, log the element's .innerHTML . If you want to see the element and its contents, log the element's .outerHTML .

 const parent = document.querySelector("div"); console.log(parent); console.log(parent.innerHTML); console.log(parent.outerHTML);
 <div>Parent <a href="#">Child</a> </div>

Well, some people say console.log() is broken , others have found that it doesn't execute immediately in chrome .

In line two, you told it to display the parent (with its child) with console.log(e.parentNode) . Which is exactly what happened but you removed that same child element it has when you introduced the third line: e.parentNode.removeChild(e) . By the time the code finish executing, it doesn't find a child anymore inside that parent element. Hence, only that node is displayed.

Just comment that part (line three) out or remove it if you want the child element to not be removed and to be displayed inside its parent.

I hope any of those links help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM