Yash009
Yash009

Reputation: 533

Trying to use javascript variable in an append statement for an a href

I have an append statement and I am trying to pass a javascript variable for the ahref attribute.But it is getting rendered as text.I want to know how do i pass the variable as a variable and not text in this append statement

jQuery('#sidr-main').append('<a class="navlink level0 addedMenu" href="abc"><li class="navlist level0">some link</li></a>');

abc is a js variable which i declared at another place and i want the value to be passed in the DOM as a variable and not the text there is no link called abc

Upvotes: 2

Views: 50

Answers (1)

Akrion
Akrion

Reputation: 18525

jQuery('#sidr-main').append('<a class="navlink level0 addedMenu" href="' + encodeURIComponent(abc) + '"><li class="navlist level0">some link</li></a>');

Make sure you do encodeURIComponent :)

In ES6 you could also use templated literal to get something more cleaner:

var str = `<a class="navlink level0 addedMenu" href="${encodeURIComponent(abc)}"><li class="navlist level0">some link</li></a>`
jQuery('#sidr-main').append(str)

Upvotes: 5

Related Questions