Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

HTML DOM access


May 09, 2021 HTML DOM


Table of contents


HTML DOM access


Access HTML DOM - Find HTML elements.


Access HTML elements (nodes)

Accessing HTML elements is equivalent to accessing nodes

You can access HTML elements in different ways, such as:

  • By using the getElementById() method
  • By TagName() method by using getElements
  • By using the getElementsByClassName() method

GetElementById() method

The getElementById() method returns an element with a specified ID:

Grammar

node .getElementById( "id" );

Here's an example to get an element of id"intro" and click "Try it" to edit it:

document.getElementById("intro");

Try it out . . .


GetElements ByTagName() method

GetElementsByTagName() returns all elements with the specified label name.

Grammar

node .getElementsByTagName( "tagname" );

The following example returns a list of all the elements in the document and clicks "Try it" to edit it:

Instance 1

document.getElementsByTagName("p");

Try it out . . .

The following example returns a list of all the elements in the document, and the elements should be descendants (children, grandchildren, etc.) of the elements of the id"main", and click "Try it" to edit:

Instance 2

document.getElementById("main").getElementsByTagName("p");

Try it out . . .


The getElementsByClassName() Method

If you want to find all HTML elements with the same class name, you can use this method to find:

document.getElementsByClassName("intro");

The example above returns a list of all the elements that contain class"intro":

Note: GetElementsByClassName() is not valid in Internet Explorer 5,6,7,8.