Accessing DOM Elements
The DOM model represents a document with a logical tree . The tree structure is called a node-tree. Each branch of the tree ends in a node, and each node contains objects. All nodes can be accessed through the tree. Their contents can be modified or deleted , and new elements can be created.
The Document Object represents the HTML document itself. It describes the objects (or nodes) that make up the document structure, and the interfaces that enable document objects to be accessed and manipulated by scripts and programs. 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.
The most common way to select an element is the document.getElementById method. Each element in a HTML document can have an optional ID attribute, which must be unique. This method takes a ID string and returns the reference to the element with the ID, or null if there is no such element. 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() - Finding by ID
- getElementsByClassName()- Finding by Class
- getElementsByTagName() - Finding by Tag
- querySelector() - Finding by Selector (single)
- querySelectorAll() - Finding by Selector (all)
Document Object Model
The getElementsByTagName() method returns a collection of an elements' child elements with the specified tag name, as a NodeList object.
The getElementsByClassName() returns an array-like object of all child elements which have all of the given class names.
The above program first alert 2, the number of p elements, and then it change the first p element's text to "First Paragraph changed !!".
querySelector() returns the first element within the document that matches the specified group of selectors, or null if no matches are found.
querySelectorAll() returns a list of the elements that match the specified group of selectors in source order. Since it is a static collection, the modification of the document has no effect on the collection.