Language: EN

modificar-elementos-del-dom-javascript

Modify DOM Elements with JavaScript

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.

Modify the content of elements

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

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';

innerHTML

The innerHTML property allows you to modify the HTML content within 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>';

Security

When using innerHTML, be cautious with inserting 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.

Modify attributes of elements

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

setAttribute()

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

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

getAttribute()

The getAttribute() method is used to retrieve 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'

Direct modification

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

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