www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons JavaScript: Adding and Removing HTML Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
Lesson 24
Lesson 25
Lesson 26
Lesson 27
Lesson 28
Lesson 29
Lesson 30
Lesson 31
Lesson 32
Lesson 33
Lesson 34
Lesson 35
Lesson 36
Lesson 37
Lesson 38
Lesson 39
Lesson 40
Lesson 41
Lesson 42
Lesson 43
Lesson 44
Lesson 45
Lesson 46
Lesson 47
Lesson 48
Lesson 49
Using JavaScript we can add and / or remove HTML elements from an HTML web page.

Adding New HTML Elements To add a new element to the HTML DOM, we must first create the element and then append it to an existing element.

The following example demonstrates this idea:

<div id="addition">
<p id="para1">This example adds a new HTML Element to a web page. </p>
<p id="para2">New element would be inserted below:</p>
</div>

<script>
var newPara=document.createElement("p");
var node=document.createTextNode("This text is surrounded with a <p> tag ");
para.appendChild(node);

var element=document.getElementById("addition");
element.appendChild(para2);
</script>


The code above creates a new <p> element and then adds text to it. To add text to the <p> element above, we have to create a text node first. Then we append the text node to the newly created <p> tag. Finally the <p> element is appended to an existing element.

Removing Existing HTML Elements
Before removing an existing element from the HTML web page, we need to know the parent of that element. The following example demonstrates the process of removing an existing HTML element from a web page:

<div id="removalEx">
<p id="para1">This is para 1.</p>
<p id="para2">This is para 2.</p>
</div>

<script>
var parentElement=document.getElementById("removalEx");
var childElement=document.getElementById("para1");
parentElement.removeChild(childElement);
</script>

The above example has a <div> tag having two child elements, also called nodes. First we find the parent element and the child element. Finally we remove the child element using the removeChild() function of the parentElement passing it the variable containing a reference to the child element.

We can also remove the child element without having to find the parent element. the following code does just that:

var childElement = document.getElementById("para2");
childElement.parentNode.removeChild(childElement);

Next >>> Lesson No. 49: JavaScript: Writing Good Code





Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.