how to assign html code in javascript variable?

Asked

Viewed 144 times

1

I want to assign that code

<div class="menu">...</div>

to a JS variable, like this :

var Code = '<div class="menu">...</div>
  • I want to assign a code hmtl inside a variable for, which I do print afterwards, just // Document.write(varialvelHtml)

2 answers

3


If you have only one element with the class on the page, you can do so:

var Code = document.body.querySelector(".menu");

If there are more, you must specify an index, with querySelectorAll:

var Code = document.body.querySelectorAll(".menu")[1];

The where the [1] represents the second element of the page with the class .menu.


The above examples will select the element as an object. If you want to take HTML, add .outerHTML:

var Code = document.body.querySelector(".menu").outerHTML;

or

var Code = document.body.querySelectorAll(".menu")[1].outerHTML;

If you want to take the internal HTML of the element:

var Code = document.body.querySelector(".menu").innerHTML;

or

var Code = document.body.querySelectorAll(".menu")[1].innerHTML;

Remembering that the index [1] is an example of the second element with the class .menu, when there is more than 1 element with the same class.

0

If you want to take an html code and assign a variable call it by an id, class, tag name or something:

var code = document.getElementsByClassName('menu')[0]

console.log(code)
<div class="menu">...</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.