Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Dom Elements in JavaScript

Dom Elements in JavaScript

? DOM Elements in JavaScript


What are DOM Elements?

  • A DOM Element represents an HTML tag (like <div>, <p>, <button>, etc.) in the Document Object Model.

  • Elements have properties (like id, className, innerHTML) and methods (like appendChild(), remove(), setAttribute()) to interact with them.

  • Elements are the main building blocks of the webpage content you manipulate with JavaScript.


How to Access DOM Elements?

1. By ID

const elem = document.getElementById("myElement");

2. By Class Name

const elems = document.getElementsByClassName("myClass");  // Returns HTMLCollection

3. By Tag Name

const elems = document.getElementsByTagName("p");  // Returns HTMLCollection

4. By CSS Selectors

const elem = document.querySelector(".myClass");       // First matching elementconst elems = document.querySelectorAll(".myClass");   // NodeList of all matching elements

Common DOM Element Properties

PropertyDescriptionExample
idElement's IDelem.id = "header"
classNameSpace-separated class nameselem.className = "active"
innerHTMLHTML content inside the elementelem.innerHTML = "<b>Hi</b>"
textContentText content inside the elementelem.textContent = "Hello"
styleInline CSS styleselem.style.color = "red"
attributesCollection of attributeselem.getAttribute("href")

Common DOM Element Methods

MethodDescriptionExample
appendChild(node)Adds a child nodeelem.appendChild(newNode)
remove()Removes the element from the DOMelem.remove()
setAttribute(name, val)Sets an attributeelem.setAttribute("src", "img.jpg")
getAttribute(name)Gets the value of an attributeelem.getAttribute("alt")
classList.add(class)Adds a CSS classelem.classList.add("visible")
classList.remove(class)Removes a CSS classelem.classList.remove("hidden")

Example: Creating and Adding a New Element

const newDiv = document.createElement("div");newDiv.textContent = "Hello World!";newDiv.classList.add("greeting");document.body.appendChild(newDiv);

Example: Changing Element Content and Style

const header = document.querySelector("h1");header.textContent = "Welcome!";header.style.color = "green";

Summary

  • DOM Elements are JavaScript objects representing HTML tags.

  • You can select, modify, add, and remove elements using DOM properties and methods.

  • DOM manipulation is core to dynamic, interactive web pages.


Want to explore event handling on DOM elements or traversing between elements (parent, children, siblings)?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql