modificar-elementos-del-dom-javascript

Modify DOM Elements with JavaScript

  • 2 min

One of the operations we will perform most frequently when working with the DOM is modifying the available elements.

Modifications can include:

  • Changing the content of elements.
  • Changing the attributes of elements.

Modifying Element Content

CommandDescription
textContentChanges the visible text of an element by replacing all textual content.
innerHTMLModifies the HTML content inside an element, allowing you to add HTML tags dynamically.

textContent

The textContent property allows you to change the visible text of an element. This method replaces all text content within the selected element.

const elemento = document.getElementById('mi-elemento');
elemento.textContent = 'New text content';
Copied!

innerHTML

The innerHTML property allows you to modify the HTML content inside an element. This includes HTML tags and text. It is useful for adding dynamic content, but you must be careful with code injection to avoid security vulnerabilities.

const elemento = document.getElementById('mi-elemento');
elemento.innerHTML = '<strong>Bold text</strong>';
Copied!

Security

When using innerHTML, be careful with the insertion of dynamic data to avoid security vulnerabilities, such as XSS (Cross-Site Scripting) attacks. Validate and escape any user input data before including it in the DOM.

Modifying Element Attributes

CommandDescription
setAttribute()Changes or sets an attribute value on an HTML element.
getAttribute()Gets the value of an attribute from an HTML element.
Direct ModificationDirectly changes properties like src, href, className on an HTML element through assignment.

setAttribute()

The setAttribute() method allows you to change the value of an attribute of an HTML element. You can set any valid attribute of an element.

const elemento = document.getElementById('mi-elemento');
elemento.setAttribute('data-info', 'value');
Copied!

getAttribute()

The getAttribute() method is used to get the value of an attribute from an element. This can be useful for reading values and performing operations based on them.

const elemento = document.getElementById('mi-elemento');
const valor = elemento.getAttribute('data-info');
console.log(valor); // 'value'
Copied!

Direct Modification

Some attributes can also be modified directly as properties of the object. For example, src, href, and className.

const imagen = document.getElementById('mi-imagen');
imagen.src = 'new-photo.jpg';
Copied!