R3gi R3gi - 6 months ago 11
Javascript Question

How to insert js/jquery variable iside HTML tag?

Let's say that I have a variable,

var sticky_element = ".menu";


and the following line of code:

jQuery(sticky_element).wrapInner('<div class="menu-inner"></div>');


How can I replace the
menu
in
class="menu-inner"
with the variable
sticky_element
?

It seems following solution doesn't work. Why?

$(sticky_element).wrapInner('<div class="' + sticky_element + '-inner"></div>');

Answer

Look at your variable declaration.

var sticky_element = ".menu";

is not the same as "menu", which you're trying to substitute with sticky_element. More explicitly,

sticky_element = ".menu" != "menu"

Omit the period from your variable string by defining

var sticky_element = "menu";

to find that this works.

Comments