0

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 '#'
1
  • 1
    That looks like the right way to me. Commented Apr 18, 2009 at 8:41

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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');

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.