Seppia Anthony Seppia Anthony - 1 month ago 11
jQuery Question

jQuery, pass a variable to append()

This one works, actually:

$('.open-submenu > a').append("<span class='open-submenu-sym'>+</span>");


I would like to change the former to:

var open-string = "<span class='open-submenu-sym'>+</span>";
$('.open-submenu > a').append(open-string);


but it seems not working...I tried also
$('.open-submenu > a').append('' + open-string);
and
$('.open-submenu > a').append("" + open-string);
but still doesn't work...is it possible to accomplish that?

Answer

The variable name is invalid since it includes - in your variable name. To make it valid replace the - character from the variable name.

var open_string = "<span class='open-submenu-sym'>+</span>";
$('.open-submenu > a').append(open_string);


For more info : What characters are valid for JavaScript variable names?

MDN Docs : Variables