Manupulating Content using DOM
The DOM (Document Object Model) allows us to interact with and manipulate the content, structure, and styles of an HTML document. Using JavaScript, we can dynamically update the page content, modify attributes, change styles, and manage classes of elements.
Here are key ways to manipulate a document using the DOM:
1. Manipulating Content
innerText
:
Retrieves or sets the text inside an element, ignoring HTML tags.
It reflects the text that the user sees, as it respects styles like
display: none
.
innerHTML
:
Retrieves or sets the HTML content inside an element, allowing you to insert HTML elements as part of the content.
It parses HTML, which makes it useful when you want to manipulate entire HTML structures.
textContent
:
- Retrieves or sets the raw text content of an element, without parsing any HTML tags. This method outputs everything, including hidden text.
<p class="text">
This is a paragraph. <b>bold</b> text and <i>Italic</i> text
</p>
2. Manipulating Attributes
Attributes like id, class
, src
, href
, and alt
can be accessed and modified using the DOM.
getAttribute()
:
- Retrieves the value of an attribute.
setAttribute()
:
- Modifies or sets a new value for an attribute.
<!DOCTYPE html>
<html>
<body>
<p class="text">
This is a paragraph. <b>bold</b> text and <i>Italic</i> text
</p>
<img id="image" src="image1.jpg" alt="Image" />
<script src="index.js"></script>
</body>
</html>
3. Manipulating Styles Using style
Attribute
You can change CSS styles directly on an element using the style
property.
Syntax:
element.style.property = "value";
4. Using the classList
Property
The classList
property allows you to add, remove, toggle, and check classes in an element's class
attribute.
Adding a Class:element.classList.add("newClass");
Removing a Class:element.classList.remove("existingClass");
Toggling a Class:element.classList.toggle("className");
it give true or false valuetrue
→ if the class is addedfalse
→ if the class is removed
Summary of Methods:
innerText
: Gets/sets visible text of an element.innerHTML
: Gets/sets HTML content, including tags.textContent
: Gets/sets raw text, including hidden text.getAttribute()
: Retrieves the value of an attribute.setAttribute()
: Sets or modifies an attribute.style
: Modifies the inline CSS of an element.classList
: Adds, removes, or toggles classes on an element.
Subscribe to my newsletter
Read articles from dheeraj koranga directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by