views:

170

answers:

3

This is a simple question that hopefully has a similar simple answer to it as well.

If the id of a div selector is stored in a string, how can I select the div object dynamically.

This is what I currently do, and I am convinced that jQuery must have its own way of doing this:

<div id="boo">Some content...</div>

var divName = 'boo';
var divObj  = $('#' + divName);  // I really don't like the concatenation of '#'
+5  A: 

I assume you mean the id of the div, which is actually different to the name, but what you've got there is accurate and not that intrusive. I'd stick with that.

nickf
+2  A: 

You could also make a simple helper function if you want to:

var $E = function( id ) {
    return jQuery('#' + id);
};
// usage:
$E('myElement').css('background-color', 'red');
moff
+1  A: 

If you really talking about ID, not name attribute, than mentione by you example is good way to do it, I don't see anything mad in this solution.

If you want to use name attribute than do it like this:

var divObj = $("div[name='"+ divName +"']");

But name attribute is usually used in form input fields.

Vladimir Prudnikov