R3gi R3gi - 2 years ago 89
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
with the variable

It seems following solution doesn't work. Why?

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download