document.write()
This method is only suitable for writing content to the page during page loading . If you use this method after the page is loaded , Will overwrite all contents of the page .
<!-- Omit some codes --> <body> <div> I am div Contents in the label </div> <p> I am p Contents in the label </p>
<button> click </button></br> <script>
document.write(" I passed during page load write() Method write ");
document.querySelector('button').addEventListener('click', function() {
document.write(" I write by clicking the button , And covers all the contents of the page !"); }) </script> </body>
results of enforcement :
Element.innerText()
This method is only suitable for writing plain text content to the page , And all contents under the element node will be overwritten .
<body> <button> click </button></br> <p> I am p Contents in the label </p>
<div> I am div Contents in the label </div> <script>
document.querySelector('button').addEventListener('click', function() {
document.querySelector('p').innerText = " I am p Contents in the label ";
document.querySelector('div').innerText = "<span> I wish div Added to the label span label </span>";
}); </script> </body>
results of enforcement :
Element.innerHTML()
This method can write text content to the page , Element contents can also be written , And all contents under the element node will be overwritten .
// Modify the above code document.querySelector('button').addEventListener('click',
function() { document.querySelector('p').innerHTML = " I am p Contents in the label ";
document.querySelector('div').innerHTML = "<span> I wish div Added to the label span label </span>"; });
results of enforcement :
document.createElement()
Elements created using this method , Need to pass appendChild(),insertBefore() or replaceChild() Method to the specified document tree node ,
Do not overwrite existing elements .
<body> <button> click </button></br> <p> I am p Contents in the label </p>
<div> I am div Contents in the label </div> <script>
document.querySelector('button').addEventListener('click', function() {
let span = document.createElement('span'); span.innerHTML =
" I created it span node , Will be added to div In label .";
document.querySelector('div').appendChild(document.createElement('br'));
document.querySelector('div').appendChild(span); }); </script>
</body>
results of enforcement :
Technology
Daily Recommendation