HTML DOM methods



Methods are actions we can perform on nodes (HTML elements).


Programming interface

The HTML DOM can be accessed through JavaScript (and other programming languages).

All HTML elements are defined as objects, and the programming interface is object methods and object properties.

Methods are actions you can perform (such as adding or modifying elements).

Attributes are values ​​that you can get or set (such as the name or content of a node).


getElementById() method

getElementById() method returns the element with the specified ID:

Instance

<html><!DOCTYPE html>
<html>
<body>

<p id="intro">Hello World!</p>
<p>This example demonstrates the <b>getElementById</b> method!</p>

<script>
x=document.getElementById("intro");
document.write("<p>The text from the intro paragraph: " + x.innerHTML + "</p>");
</script>

</body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance


HTML DOM Object - Methods and Properties

Some commonly used HTML DOM methods:

  • ##getElementById(id) - Get the node with the specified id (element)

  • appendChild(node) - Insert a new child node (element)

  • removeChild(node) - Remove a child node (element) )

Some commonly used HTML DOM attributes:

  • innerHTML - the text value of the node (element)

  • parentNode - the parent node of the node (element)

  • childNodes - the child node of the node (element)

  • attributes - the node (element) )'s attribute node

#You will learn more about attributes in the next chapter of this tutorial.


Objects in real life

A person is an object.

Human methods may be eat(), sleep(), work(), play(), etc.

All have these methods but execute them at different times.

A person's attributes include name, height, weight, age, gender, etc.

All humans have these attributes, but their values ​​vary from person to person.


Some DOM Object Methods

Here are some common methods you will learn in this tutorial:

MethodsDescriptiongetElementById()Returns the element with the specified ID. getElementsByTagName()Returns a node list (collection/node array) containing all elements with the specified tag name. getElementsByClassName()Returns a node list containing all elements with the specified class name. appendChild()Add a new child node to the specified node. removeChild()Delete child nodes. replaceChild()Replace child node. insertBefore()Insert a new child node before the specified child node. createAttribute()Create an attribute node. createElement()Create element node. createTextNode()Create a text node. getAttribute()Returns the specified attribute value. setAttribute() Set or modify the specified attribute to the specified value.