How to add and delete the html elements in JavaScript?

Asked 19-Jul-2021
Viewed 264 times

0

How to add and delete the html elements in JavaScript?


1 Answer


1

Adding and Deleting Elements

In JavaScript, we are create new html elements, append new html elements, replace the elements and remove the existing elements.

  1. document.createElement(element)     Create an HTML element
  2. document.removeChild(element)         Remove an HTML element
  3. document.appendChild(element)         Add an HTML element
  4. document.replaceChild(new, old)          Replace an HTML element
  5. document.write(text)                                 Write into the HTML output stream

document.createElement(element)

It's is used to create the new element and append in the document by using appendChild().

<html>

<body>
<p>Click the button to make a BUTTON element with text.</p>
<button onclick='myFunction()'>Try it</button>
<script>
    function myFunction() {
        // create the new button element
        var btn = document.createElement('BUTTON');
        // change the innerhtml of button
        btn.innerHTML = 'CLICK ME';
        // appent the button in body section in documents
        document.body.appendChild(btn);
    }
</script>
</body>
</html>

document.removeChild(element)

this function use to remove elements form document.

<!DOCTYPE html>

<html>
<body>
<ul id='myList'>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<p>Click the button to remove the first item from the list.</p>
<button onclick='myFunction()'>Try it</button>
<script>
function myFunction() {
  var list = document.getElementById('myList');
  list.removeChild(list.childNodes[0]);
}
</script>
</body>
</html>


Loading...
Ads