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
Tips and tricks for USING THE DOM API
Build to-do list web-app with code
Using more than one CSS property
W3School HTML DOM removeChild() Method