Skip to main content

JavaScript HTML DOM Changing HTML

JavaScript provides a variety of methods for changing the HTML content of an element in the Document Object Model (DOM).

Here are a few examples:

Changing the text content of an element​

To change the text content of an HTML element, you can use the textContent property.

As an example:

Editor

Loading...

In this example:

  • The getElementById() method is used to get the <p> element with the ID "myParagraph".
  • The textContent property is then used to change the text content of the element to "This paragraph has been changed.".

Changing the HTML content of an element​

To change the HTML content of an element, you can use the innerHTML property.

As an example:

Editor

Loading...

In this example:

  • The getElementById() method is used to get the <p> element with the ID "myParagraph".
  • The innerHTML property is then used to change the HTML content of the element to "<em>This paragraph</em> has been changed.".

Changing the value of an input element​

To change the value of an input element, you can use the value property.

As an example:

Editor

Loading...

In this example:

  • The getElementById() method is used to get the <input> element with the ID "myInput".
  • The value property is then used to change the value of the element to "New value".

Changing the src attribute of an image element​

To change the source (src) attribute of an image element, you can use the setAttribute() method.

As an example:

Editor

Loading...

In this example:

  • The getElementById() method is used to get the <img> element with the ID "myImage".
  • The setAttribute() method is then used to change the src attribute of the element to "image2.jpg".

Changing the style of an element​

To change the style of an HTML element, you can use the style property to access the inline style of the element.

As an example:

Editor

Loading...

In this example:

  • The getElementById() method is used to get the <p> element with the ID "myParagraph".
  • The style property is then used to change the color of the text to "blue" and the font size to "20px".

Changing the class of an element​

To change the class of an HTML element, you can use the className property.

As an example:

Editor

Loading...

In this example:

  • The getElementById() method is used to get the <p> element with the ID "myParagraph".
  • The className property is then used to change the class of the element from "oldClass" to "newClass".