DEV Community

Anandhi P
Anandhi P

Posted on

DOM IN JAVASCRIPT

What is DOM?

DOM stands for Document Object Model.

DOM is used to access and change HTML elements using JavaScript.

When a web page loads, the browser creates a DOM structure for the HTML page.

Using DOM, we can change:

  • HTML text
  • HTML styles
  • HTML attributes
  • HTML elements

Simple Example

<h1 id="title">Hello</h1>

<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
    document.getElementById("title").innerText = "Welcome";
}
</script>
Enter fullscreen mode Exit fullscreen mode

How it works

  1. <h1> contains Hello.
  2. getElementById("title") finds the <h1> element.
  3. innerText changes the text.
  4. When we click the button, Hello changes to Welcome.

Simple Definition

DOM = Using JavaScript to access and change HTML elements.
HTML has

→ Hello
JavaScript finds it using getElementById()
innerText changes the text
Click the button → Welcome appears.

Style

style is used to change the CSS style of an HTML element using JavaScript.

Example

Hello

document.getElementById("title").style.color = "red";

Now the Hello text will appear in red.

We can change different styles:

element.style.color = "red";
element.style.backgroundColor = "yellow";
element.style.fontSize = "30px";

InnerText

innerText is used to get or change the text inside an HTML element.

Example

Hello

document.getElementById("title").innerText = "Welcome";

Before:

Hello

After:

Welcome

querySelector()

querySelector() is used to find the first matching HTML element.

Example

Hello

let element = document.querySelector(".text");
element.innerText = "Welcome";

Output:

Welcome

→ ID

. → Class

document.querySelector("#title");
document.querySelector(".text");

Top comments (0)