DOM Elements in JavaScript

Filter Course


DOM Elements in JavaScript

Published by: Sujan

Published date: 16 Jun 2021

DOM Elements in JavaScript -Photo

DOM Elements in JavaScript

JavaScript DOM Elements is most commonly used to get or modify the content or value of the HTML elements on the page, as well as to apply some effects like the show, hide, animations, etc. But, before you can perform any action you need to find or select the target HTML element.

Selecting the Topmost Elements

The topmost elements in an HTML document are available directly as document properties. For example, the

element can be accessed with document.documentElement property, whereas theelement can be accessed with document.head property, and the

element can be accessed with document.body property. Here's an example:

DOM Elements in JavaScript

Selecting Elements by ID

You can select an element based on its unique ID with
the getElementById() method. This is the easiest way to find an HTML element in the DOM tree.

The following example selects and highlights an element having the ID attribute id="mark".

DOM Elements in JavaScript

The getElementById() method will return the element as an object if the matching element was found, or null if no matching element was found in the document.

Selecting Elements by Class Name

Similarly, you can use the getElementsByClassName() method to select all the elements having specific class names. This method returns an array-like object of all child elements which have all of the given class names.

DOM Elements in JavaScript

Setting Inline Styles on Elements

Inline-styles are applied directly to the specific HTML element using the style attribute. In JavaScript, the style property is used to get or set the inline style of an element.

The following example will set the color and font properties of an element with id="intro".

DOM Elements in JavaScript