DOM Access

Javascript DOM Access

The document object represents a web document or page. It represents a document as a hierarchical tree structure and each element in the document tree is called a Node in the DOM (Document Object Model).

Structurally, the Document Object Model consists of nodes, with each node representing content in the web document. It gives developers a way of representing everything on a web page so that the contents of the web page is accessible via a common set of properties and methods.

DOM Methods

The getElementById() and getElementsByTagName() were the two methods from DOM standard and the HTML5 specification adds three new methods for accessing elements, getElementsByClassName(), querySelector(), and querySelectorAll().

getElementById()

Javascript DOM getElementById

Typically you want to access an element within the DOM directly and try to do something with it. Javascript provides a document.getElementById() method, which is the easiest way to access an element from the DOM tree structure. It will return the element that has the ID attribute with the specified value.

Document Object Model

Source

Above program returns "Document Object Model" .

getElementsByTagName

The getElementsByTagName() is one of the method exposes for accessing nodes directly. This method takes a tag name as argument and returns a collection of all the nodes it finds in the document that are a sort of tag.

Paragraph 1

Paragraph 2

Paragraph 3

Paragraph 4


Above program returns 4 , because total 4 paragraph elements in the HTML page.

getElementsByClassName()

The getElementsByClass() method works same like getElementById() method, and it will returns a collection of all elements in the document with the specified class name.

Paragraph 1

Paragraph 2

Paragraph 3

Paragraph 4

Full Source

The above program first alert 4, the number of p elements, and then it change the second p element's text to "Second Paragraph".

Both querySelector() and querySelectorAll() methods let you enter a CSS selector as an argument and return the selected elements as DOM elements.

querySelector()

It will returns the first element that matches a specified CSS selector in the document.

Paragraph 1

Paragraph 2

Paragraph 3

Paragraph 4

Full Source

Above program change the first paragraph text to "First Paragraph".

querySelectorAll()

The querySelectorAll() method returns a collection filled with the matching elements in source order. Since it is a static collection, the modification of the document has no effect on the collection

div content 1

Paragraph 2

Full Source


Javascript DOM element

When you run the above code, you can see the place of the second p element text is changed but the p element remains there (the change you can see at the top line of browser only).