DOM Manipulation with Javascript

Página 8

The manipulation of the DOM (Document Object Model) is one of the main features of Javascript in the development of web sites. The DOM is an in-memory representation of the HTML document, which allows JavaScript to dynamically access and modify page elements.

To manipulate the DOM with Javascript, you must first select the desired HTML element. This can be done in several ways, such as through the element ID, CSS class or tag type. Once the element is selected, it is possible to access its properties and methods to carry out the desired manipulation.

For example, to change the content of an HTML element, you can use the innerHTML property. See example below:


// Select element with ID "title"
var title = document.getElementById("title");

// Change the content of the element
titulo.innerHTML = "New Title";

In addition to changing the content of elements, you can also modify their properties, such as CSS style. To do so, you can use the style property, which allows you to access and modify the element's style properties. See example below:


// Select element with ID "paragraph"
var paragraph = document.getElementById("paragraph");

// Change the text color of the paragraph to red
paragraph.style.color = "red";

Another way to manipulate the DOM with Javascript is through the creation and removal of HTML elements. For that, you can use the methods createElement and removeChild, respectively. See example below:


// Create a new "div" element
var newDiv = document.createElement("div");

// Adds the new element to the end of the body
document.body.appendChild(newDiv);

// Remove element with ID "paragraph"
var paragraph = document.getElementById("paragraph");
document.body.removeChild(paragraph);

Finally, it is important to remember that manipulating the DOM with Javascript can be a complex task and requires a good knowledge of the HTML structure and how Javascript works. It is recommended to use libraries such as jQuery, which facilitate manipulation of the DOM and offer a simpler and more intuitive syntax.

Now answer the exercise about the content:

_What is the property that allows accessing and modifying the style properties of the HTML element in Javascript?

You are right! Congratulations, now go to the next page

You missed! Try again.

Next page of the Free Ebook:

9Events in Javascript

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text