jquery variable as div ID or class

16,867

You would go about it in the same way as normal JavaScript (since it's just a string passed to jQuery).

var name = 'amuchlongername'
$('#wrapper').prepend('<div id="' + name + '"></div>');

name is just a normal JavaScript variable and can be anything. The $ is an alias for jQuery. When you do $('#wrapper') you are calling jQuery to access the element with the Id of wrapper.

I've made a jsFiddle to show it working: http://jsfiddle.net/Xs45x/1/ I've just updated it to put the variable inside the div too, so you can see what it's doing.

Share:
16,867
Daryl
Author by

Daryl

Updated on June 04, 2022

Comments

  • Daryl
    Daryl almost 2 years
    var $name = ('div#amuchlongername');
    
        $('#wrapper').prepend('<div id="$name"></div>');
    

    Obviously I know this code is wrong lol, but I'm fairly knew to jQuery and I can't seem to find anything about this.

    How would one go about achieving a variable name inside a div id?

  • Jonathon Bolster
    Jonathon Bolster over 13 years
    You're correct. In JavaScript you don't need to have $ on variable names. However, to access the element using jQuery (usually by the $) you'll need the $ on the ('#wrapper') bit - i.e. $('#wrapper')
  • Daryl
    Daryl over 13 years
    I havent tested it, but it seems to make sense. So you don't need the (''); for the variables either then?
  • Jamiec
    Jamiec over 13 years
    Using a $variablename is just a convention when dealing with jQuery objects - and a good one IMO.
  • Daryl
    Daryl over 13 years
    Ideal, makes sense now. It's always the most simple thing haha. I'll get there in the end. =]
  • Jonathon Bolster
    Jonathon Bolster over 13 years
    +1 Not a convention I knew about but it makes sense for the jQuery objects - thanks. In this case though, the variable is just a normal string.
  • Jonathon Bolster
    Jonathon Bolster over 13 years
    Great! Note that name is just a string. If you wanted to use jQuery on the new element you could do var $myNewDiv = $('#amuchlongername') or even just var $myNewDiv = $(name); since name is a string. As mentioned in the comment by Jamiec, the $ isn't required on the variable name but is a nice notation for jQuery objects.