isar
isar

Reputation: 1791

JavaScript ID tag selection

Is there a better way to write jQuery('#'+ myId) in JavaScript. I have an ID in a variable without the # character and jQuery('#'+ myId) looks ugly.

var myId = 'last-element-id';
jQuery('#'+ myId)

I'd like to avoid the + character to join the strings. Thanks

Upvotes: 2

Views: 57

Answers (4)

Mehdi Dehghani
Mehdi Dehghani

Reputation: 11601

I think when you are using jQuery, is better you stick with jQuery in all your code. My offer is, create a function as below:

var getId = function(id){
    return '#'+ id;
}

and call that anywhere you need, and stick with jQuery. like this:

$(getId(id));

Upvotes: 0

Sai Kiran Sripada
Sai Kiran Sripada

Reputation: 1147

As simple as that:

var myId = '#last-element-id';
jQuery(myId);

or

var myId = '#' + 'last-element-id'; // if 'last-element-id' is dynamically generated value
jQuery(myId);

Upvotes: 0

Krzysztof Safjanowski
Krzysztof Safjanowski

Reputation: 7438

But, have in mind that returned element is not a jQuery collection

function getElement(element) {
    return document.getElementById(element)
}

Upvotes: 1

AmmarCSE
AmmarCSE

Reputation: 30557

function jQueryID(myId){
    return jQuery('#'+ myId);
}

and then call like

jQueryId(myId);

Upvotes: 0

Related Questions