Create Element And Append Child Method


In this lesson we learn how can we dynamically add the content to alert page after its has been loaded into the browser but these changes are not permanent we don't able to save these changes to HTML, these are just for use after HTML page download on the browser, So lets get started.

We create an var el for store our new element because its must to store into a variable than we use createMethod for create a new Element, we can create any type of element like p, div, hr, h1 etc. but this very must to create an element before to add because if we haven't create an element so it can be easy to understand that how can we add new element without create. In simple manner we can say createElement is just use for create a new element we can decide what kind of element is this than we use appendChild method, this is use for add any element in anywhere we want.


createNewElement

Another Example :

(function(){
var el = document.createElement("p"),
content = document.createTextNode("paragraph 3");
el.appendChild(content);
el.setAttribute("align", "right");
document.body.appendChild(el);
}());

We talk about before that we have all kind of node list so here we are using a text node and We also can use innerHTML on behalf of document.createTextNode they both works same. Here we add an new Object setAttribute it's stands for set property in paragraph element. If we want to set an id for particular item than we also can set as el.id = "foo" ;


Let see some more functionality :

Settingupattributes

Here d = document, nE = newElement, c = content, pFoo = access foo id of div p element by using = document.getElementById("foo"); method.

Note : There is one more method for replacing items: pFoo.parentNode.replaceChild(el, pFoo); // Replace p Element of foo id with new Element or p Element with bar id.

innerHTML

InnerHTML is the final topic of this lesson. Several times we use the innerHTML method but finally we are going to discuss this with an example actually this is a very easy and useful way to replace and access the properties with clean way.

innerHTML

Note: When we several times use document Objects and createElements etc. than we are actually dealing with DOM and DOM takes more memory than HTML. So we can sought out this problem by putting our Objects and methods into var and than if we use them again and again they work faster with this trick, our web page is going lighter and we can access them easily so putting values into var is a good practice.


Wconcert India © 2015   ·   All Rights Reserved

Free Web Hosting