We can get and change the outerHTML of an element using JavaScript. We can use the JavaScript getElementById() method to target the outerHTML property of an element.

document.getElementById("p1").outerHTML

Let’s see an example of this below.


Let’s say we have the following HTML:

This is a paragraph with some text.


If we want to get the outerHTML of a paragraph with id, #p1, we can use our code from above to do this.

console.log(document.getElementById("p1").outerHTML);

#Output
//

This is a paragraph with some text.


Let’s take a look at changing the outerHTML of an element using JavaScript in our next example.

Changing outerHTML of an Element using JavaScript

Changing the outerHTML of an element will essentially replace the element with whatever new HTML element you want.

Let’s take a look at some simple HTML code again:

This is our first paragraph with some text.

This is our second paragraph with some text.

This is a paragraph that we will want to change.

Change last pargraph

In our HTML above, we will want to change the last paragraph with id #p7 and text “This is a paragraph that we will want to change.”. To do this, we will use the JavaScript getElementById() method to target that p element and target its outerHTML property. We will create a function that will run when the user clicks our button to run this code.

Here is our JavaScript code to change the outerHTML of an element:


document.getElementById("p7").outerHTML = "

This is our third paragraph with some text.

“;

And here is the JavaScript code in our function:

function changeOuterHTML(){
  document.getElementById("p7").outerHTML = "

This is our third paragraph with some text.

“; };

The final code and output for this example of how to change the outerHTML of an element using Javascript is below:

Code Output:

This is our first paragraph with some text.

This is our second paragraph with some text.

This is a paragraph that we will want to change.

Change last pargraph

Full Code:

This is our first paragraph with some text.

This is our second paragraph with some text.

This is a paragraph that we will want to change.

Change last pargraph



Hopefully this article has been useful for you to understand how to get and change the outerHTML of an element using JavaScript.

Categorized in:

HTML, JavaScript,

Last Update: May 3, 2024