0

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.

user690421
  • 422
  • 1
  • 5
  • 15
  • there is not... another option is `$(document.getElementById(id))`.... but seriously what is wrong with a string concatenation? – Arun P Johny Feb 27 '14 at 00:04
  • 4
    *"The problem of using `$('#' + id)` is that the string concatenation doesn't seems to be good coding style."* String concatenation is the only way to build dynamic selectors, and there are valid use cases for that. I wouldn't worry too much about it. I assume you are not doing something ingenious like `var id = this.id; $('#'+id)....`. – Felix Kling Feb 27 '14 at 00:04
  • @FelixKling I guess I was oversensitive. Basically, I am writing a UI tool and the id shall be extracted from another element's attribute in order to establish some relation. I was thinking about things like sql injection and felt that a more procedural way to write code is better than assembling a string. But in client-side script it shouldn't be a problem unless someone intentionally want a scrambled page. – user690421 Feb 27 '14 at 00:13

2 Answers2

2

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.

Ananthan Unni
  • 1,304
  • 9
  • 23
1

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?

Community
  • 1
  • 1
Allende
  • 1,480
  • 2
  • 22
  • 39