0

Could someone tell me how could I change the value with HTML code to a regular string? Example:

<h1>Hello world!</h1>
=> "<h1>Hello World!</h1>"

Current code:

var myH1 = document.getElementsByTagName("h1")[0];
console.log(myH1);

// Prints: <h1>Hello World!</h1> instead of "<h1>Hello World!</h1>"
<h1>Hello World!</h1>

5
  • myH1 is a HTMLElement (object). Why do you expect it to be a string? Commented Feb 26, 2021 at 11:29
  • I know but how to transfer it to string? Commented Feb 26, 2021 at 11:30
  • 3
    myH1.outerHTML Commented Feb 26, 2021 at 11:31
  • 1
    With research Commented Feb 26, 2021 at 11:31
  • ritaj, you can write it as an answer ( not as a comment ) ... thx!) Commented Feb 26, 2021 at 11:35

1 Answer 1

0

Simply you can do like this :

var myH1 = document.getElementsByTagName("h1")[0];

myH1 =`"${myH1.innerHTML}"`
console.log(myH1);

//Or

var myH1 = document.getElementsByTagName("h1")[0];
console.log(myH1.outerHTML);
 Output => "<h1>Hello world!</h1>" 

Sign up to request clarification or add additional context in comments.

3 Comments

Now, you can check : myH1 ="${myH1.innerHTML}"
The OP asked for the output to be "<h1>Hello World!</h1>" as opposed to "Hello world". I think your code should be myH1.outerHTML rather than myH1.innerHTML.
The .innerHTML part is not relevant for this question