I found a lot of examples of Dom operations on the Internet, and they felt incomplete and messy.
You may often encounter this problem as follows:
1. Create DOM elements
2. Dom element insertion
3. Dom element replacement
4. Delete DOM elements
First, there are some simple DOM elements on the page.
<Div id = "Wrap">
<Div id = "A"> aaaaaaaa </div>
<Div id = "B"> bbbbbbbbbb </div>
<Div id = "C"> ccccccccc </div>
</Div>
Next we will create a div element and JS Code:
VaR div_d = Document. createelement ('div ');
Div_d.innerhtml = "dddddddd ";
Div_d.id = "D ";
// Innertext is not used here to avoid browser compatibility issues;
Then, insert the created Div with id d to the front of the DIV with the DOM element id B.
VaR div_wrap = Document. getelementbyid ('wrap ');
VaR div_ B = Document. getelementbyid ('B ');
Div_wrap.insertbefore (div_d, div_ B );
If you directly insert a child element with the id of wrap, you can do this:
Div_wrap.insertBefore (div_d, null );
If div_ B is replaced, it is as follows:
Div_wrap.replaceChild (div_d, div_ B );
Finally, we delete the div with the specified Element id B.
Div_ B .parentNode.removeChild (div_ B );
Or
Document. body. removeChild (div_ B );
There may be many derivative methods and applications in the future.