Thursday 7 April 2016

Document object in javascript - introduction

Here is the html code that has been used in the javascript code on this page.

<article id="article1" class="my_new_class">
    <h3>
        Demonstrating how to get an element fron an html document in javascript
    </h3>
    <p>
        This is paragraph one.
    </p>
    <p>
        This is paragraph two.
    </p>
    <p class="new_point">
        This is paragraph three.
    </p>
    <p class="new_point">
        This is paragraph four.
    </p>
</article>

Here is the javascript code that uses the html code above.

var element = document.getElementById('article1');
console.log(element);//We get the element in the document that has id=article1
var elements = document.getElementsByTagName('p');
console.log(elements);//We get an array of all the elements that has a tag of p i.e., paragraph
var element = document.getElementsByTagName('h3');
console.log(element);//We get an array of all the elements with heading set to h3
var elements = document.getElementsByClassName('new_point');
console.log(elements);//We get an array of our two paragraph elements with class=new_point

//***************************************************************************
/* 
Once we get an element from a document then we can get access to any of its attributes also. 
*/
var e = document.getElementById('article1');
console.log(e.getAttribute('class'));//my_new_class

//We can dynamically set an attribute also. 
e.setAttribute('class', 'my_old_class');
console.log(e.getAttribute('class'));//my_old_class

//We can get all the child nodes of an element.
console.log(e.childNodes); /* We get on the console
[text, h3, text, p, text, p, text, p.new_point, text, p.new_point, text]
the array has text 6 times because we have spaces before the h3, and all the paragraph elements and white space is represented as text. */

No comments:

Post a Comment