Saturday, 7 October 2017

Remove all child elements of a DOM node in JavaScript

itemprop="text">

How would I go about removing all of
the child elements of a DOM node in
JavaScript?



Say I have the following (ugly)
HTML:




            id="foo">
hello

world




And
I grab the node I want like
so:



var myNode =
document.getElementById("foo");



How
could I remove the children of foo so that just

is
left?



Could I just
do:



myNode.childNodes = new
Array();


or should I
be using some combination of
removeElement?




I'd
like the answer to be straight up DOM; though extra points if you also provide an answer
in jQuery along with the DOM-only answer.


class="post-text" itemprop="text">
class="normal">Answer



Option 1
(much slower, see comments below):



class="snippet" data-lang="js" data-hide="false" data-console="true"
data-babel="false">

class="snippet-code-js lang-js prettyprint-override">doFoo.onclick = ()
=> {
const myNode = document.getElementById("foo");

myNode.innerHTML = '';

}

class="snippet-code-html lang-html prettyprint-override">
style="height: 100px; width: 100px; border: 1px solid black;">

Hello

id='doFoo'>Remove Via
innerHTML





Option
2 (much faster):




data-lang="js" data-hide="false" data-console="true"
data-babel="false">

class="snippet-code-js lang-js prettyprint-override">doFoo.onclick = ()
=> {
const myNode = document.getElementById("foo");
while
(myNode.firstChild) {
myNode.removeChild(myNode.firstChild);

}
}




Hello

id='doFoo'>Remove Via
removeChild





No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...