REMOVING A HTML ELEMENT

Let’s have a go at using the removeChild method and this keyword to remove an HTML element.

1) Open up your text-editing program. Create a new HTML file called remove.html. Code a parent and a child < div > in your < body >. Set the id attribute of the parent < div >, like this:

[html] <!DOCTYPE html>
<html>
<head>
<title>Remove Items</title>
</head>
<body>
<div id="list">
get milk
<div>
get eggs
</div>
</div>
</body>
</html>[/html]

2) Now add a JavaScript function to your < head > that will remove the

child < div > from your page. The function will find the parent < div > using the getElementById method. It will then use removeChild to remove the < div > nested inside it. Your code will look like this:

[html] <script>
function removeItem(item) {
document.getElementById("list"). removeChild(item);
}
</script>[/html]

3) Finally add an onclick attribute to the child < div >, so that when the text inside it is clicked, it will be removed from the list.

The onclick should call your function and use the this keyword, like this:

[html] <div onclick="removeItem(this);">
get eggs
</div>[/html]

4) Save your HTML file and open it in your browser. When you click on the second item, it will vanish from the screen.

 


Related Posts:

Building a web-based JavaScript game

CODING WEB PAGES (HTML, CSS, & JavaScript)

CODING WITH CSS: The style attribute

Tips and tricks for CSS coding

SAVING YOUR TO-DO LIST ITEMS to localStorage

More than one CSS class

Tips and tricks for USING THE DOM API

Build to-do list web-app with code

The color CSS property

Using more than one CSS property

Alignment CSS properties

W3School HTML DOM removeChild() Method

 

Connected through code, Choose Your Platform!

About the Author: Bernard Aybout

In the land of bytes and bits, a father of three sits, With a heart for tech and coding kits, in IT he never quits. At Magna's door, he took his stance, in Canada's wide expanse, At Karmax Heavy Stamping - Cosma's dance, he gave his career a chance. With a passion deep for teaching code, to the young minds he showed, The path where digital seeds are sowed, in critical thinking mode. But alas, not all was bright and fair, at Magna's lair, oh despair, Harassment, intimidation, a chilling air, made the workplace hard to bear. Management's maze and morale's dip, made our hero's spirit flip, In a demoralizing grip, his well-being began to slip. So he bid adieu to Magna's scene, from the division not so serene, Yet in tech, his interest keen, continues to inspire and convene.