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 <html> element can be accessed with document.documentElement property, whereas the <head> element can be accessed with document.head property, and the <body> element can be accessed with document.body property. Here’s an example:
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”.
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.
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”.
If you liked our content DOM Elements in JavaScript, then you will also like JavaScript DOM Nodes
Leave a Reply