What you will learn
- Adding, deleting and changing content to your page
- Changing elements style
- Changing elements attributes
- React to user events like click (more in events section)
What is DOM
DOM (Document Object Model) is created by the browser. It is a tree-like structure made up of all the elements that exist in your HTML document.
DOM (Document Object Model) provides a structured representation of the document (a tree) and it defines a way that the structure can be accessed from programs so that they can change the document structure, style and content. DOM is made up of all the elements that exist in your HTML document.
There are many JavaScript built-in functions, which are used to access and to manipulate DOM elements. See Manipulating documents. DOM manipulation was easier with jQuery and it is covered in jQuery lecture in this course. However jQuery popularity is going down and today it is easy to select and manipulate DOM with vanilla JavaScript. In addition by using jQuery library we have worse performance. A good resources of Vanilla JavaScript DOM functions (some with reference to jQuery) are:
- Document (great documentation)
- JavaScript Functions and Helpers to work with DOM (great resource)
- how to manage HTML DOM (great resource)
- You might not need jQuery
- Code Snippets
- The DOM of Javascript
Accessing DOM Elements
document object gives an access to the DOM. Type document in the console to see all its fields and methods. DOM access functions by JavaScript are:
- getElementById - Returns an element with the specified ID. Returns null if not found.
- getElementsByTagName - Returns an array-like object (HTMLCollection) of elements with the specified tag name. Returns an empty array if not found.
- getElementsByClassName - Returns an array-like object (HTMLCollection) of elements with the specified class name. Returns an empty array if not found.
- getElementsByName - Returns an array-like object (NodeList/HTMLCollection depends on browser) of elements with a given name in the document. Returns an empty array if not found.
- querySelector - Takes an argument, which is a CSS selector for the element you are wanting to find. The returned element is the first element it finds. Returns null if not found.
- querySelectorAll - Returns an array-like object (NodeList) of all elements it finds that match the selector you provide. Returns an empty array if not found. Note that it can get more than one selector - comma-separated list of selectors, and will match all of them.
Note: all the above functions (beside getElementById) can be used on the selected element. For example:
var ul = document.querySelector( 'ul' ); var li = ul.querySelectorAll( 'li' ); // or by chaining li = document.querySelector( 'ul' ).querySelectorAll( 'li' );
The functions getElementById, getElementsByTagName and getElementsByClassName are very specific and much faster, while querySelector and querySelectorAll are more elaborate.
The getElement methods return live DOM elements while the querySelector method does not. querySelector returns elements which are known at the time of execution of this search (will not recognize elements that are added later). Live DOM elements update as you change them by adding, removing and changing values.
Notes:
- Node list is not an array and have to be converted to array before using array iteration methods.We will see it in the following examples. Regular 'for/while/do-while' work fine with the node list. Also 'for-of' can be used
- It is important to cache selectors in variables if selection is done multiple times.
- A good approach to access DOM elements is by using data attributes. Data attributes exist solely to add additional information to an element. In the HTML spec, they have no defined meaning, which makes them incredibly flexible. See JavaScript selectors in HTML for more information.
Summary from Searching Elements:
Examples
Example - Get element by ID:
var element = document.getElementById( 'my-id' ); // or var element = document.querySelector( '#my-id' );
Example - Get elements by class name:
var elements = document.getElementsByClassName( 'my-class' ); // or var elements = document.querySelectorAll( '.my-class' ); for ( var i = 0; i < elements.length; i++ ) { var element = elements[ i ]; element.style.color = "red"; }
Example - Get elements by tag name:
var elements = document.getElementsByTagName( 'li' ); var elements = document.querySelectorAll( 'nav ul li' );
Example - use querySelectorAll:
var images = document.querySelectorAll( 'img' ); for ( var i = 0; i < images.length; i++ ) { var image = images[ i ]; alert( image.getAttribute( src ) ); }
Note: querySelector and querySelectorAll take the full range of CSS selector syntax variations as its argument.
Example - use data attribute:
<div data-expand> Some content that can be collapsed or expanded. </div> var expand = document.querySelectorAll( '[data-expand]' );
Example - use data attribute:
<div data-action="expand"> Some content that can be collapsed or expanded. </div> var expand = document.querySelectorAll( '[data-action="expand"]' );
Example:
Define a function like jQuery to get an element:
var $ = function ( selector, parent ) { return ( parent ? parent : document ).querySelector( selector ); }; var $$ = function ( selector, parent ) { return Array.prototype.slice.call( ( parent ? parent : document ).querySelectorAll( selector ) ); // ES6 // return [ ...(parent ? parent : document ).querySelectorAll( selector ) ]; }; // call example var el = $( '.my-class' ); var elArr = $$( '.my-class' );