I want to assign this code
<div class="menu">...</div>
to a JS variable, type this:
var Code = '<div class="menu">...</div>
I want to assign this code
<div class="menu">...</div>
to a JS variable, type this:
var Code = '<div class="menu">...</div>
If you only have one element with class
on the page, you can do this:
var Code = document.body.querySelector(".menu");
If they are more, you should specify an index, with querySelectorAll
:
var Code = document.body.querySelectorAll(".menu")[1];
The where [1]
represents the second element of the page with class .menu
.
The above examples will select the element as an object. If you want to get HTML, add .outerHTML
:
var Code = document.body.querySelector(".menu").outerHTML;
or
var Code = document.body.querySelectorAll(".menu")[1].outerHTML;
If you want to get the element's internal HTML:
var Code = document.body.querySelector(".menu").innerHTML;
or
var Code = document.body.querySelectorAll(".menu")[1].innerHTML;
Remembering that the
[1]
index is an example that refers to the second element with the class.menu
, when there are more than 1 element with the same class.
If you want to get an html code and assign it to a variable call it by an id, class, tag name or something like this:
var code = document.getElementsByClassName('menu')[0]
console.log(code)
<div class="menu">...</div>