How to add and delete the html elements in JavaScript?

0 votes
49 views
Ravi Vishwakarma asked 13 days ago in Web Application by Ravi Vishwakarma

How to add and delete the html elements in JavaScript?

1 Answer

0 votes
Ethan Karla answered 10 days ago by Ethan Karla

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>