user690421
user690421

Reputation: 422

Get element by ID in jquery

So basically, I want to know whether there is a function in jQuery that is similar to getElementById of vanilla javascript. The problem of using $('#' + id) is that the string concatenation doesn't seems to be good coding style.

I can definitely add my own helper method but I am just wondering whether there is already something in jQuery.

Upvotes: 0

Views: 169

Answers (2)

Allende
Allende

Reputation: 1482

This actually works:

var id="myTextBox";
alert ($(eval(id)).val());

html:

<input type='textbox' id="myTextBox" value="hola mundo"></input>

And you're not using string concat but: I wouldn't use it or encourage to under any circunstance, string concat is the way to go in this case I think.

More about eval(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

More information related here: Why is using the JavaScript eval function a bad idea?

Upvotes: 1

Ananthan Unni
Ananthan Unni

Reputation: 1304

It is as simple as the one you wrote. If you have an element with the id 'divInfo' then you can select the element by using $('#divInfo'). Its just plain CSS selector.

Upvotes: 2

Related Questions