Reputation: 8380
Is there a better way to write the following function?
Having the '#' + div_id
just looks wrong to me.
function hide_div(div_id) {
$('#' + div_id).hide();
}
Upvotes: 6
Views: 447
Reputation: 6141
No, you can't shorten it more than that. An alternative to # + div_id would be :
$('[id="'+div_id+'"]')
This query is working with [] attribute selector. Not shorter, not cleaner, really slower but an alternative anyway
Upvotes: -5
Reputation: 8859
Depending on the use case you could pass the object instead of the id:
$('#someobject').click(function(){
hideDiv(this);
});
Upvotes: 0
Reputation: 60787
Several alternative ways:
$(['#', div_id].join('')).hide();
$('#'.concat(div_id)).hide();
Also, @Thomas inspired me for this alternative solution:
When you call your function, use:
$.proxy( hide_div, $('#' + div_id) );
// Then, you can do this:
function hide_div() {
this.hide();
}
It may allow you for better reuse. Or not.
Upvotes: 2
Reputation: 6267
Short answer: no. Slightly longer and more hackish answer: create a function with a one-letter long name that takes the element's ID and returns a getElementById on it, then wrap that in your jQuery $()
, like so:
function i(id) {
if (document.getElementById(id)) return document.getElementById(id);
else return "";
}
Then:
$(i(id)).doWhatever();
But honestly, think about it:
$("#" + id)
12345678
$(i(id))
12345
That's three characters. Is it worth it? Do those three characters really matter that much to you? You're already saving a lot by not using document.getElementById(id) (27 characters).
Upvotes: 4
Reputation: 142977
If you are somehow opposed to the string concatenation, then you could do this instead:
$(document.getElementById(div_id)).hide();
You could also pass in the fully qualified selector, like this:
hide_div("#divId");
If you wanted to do it in vanilla Javascript, you could do this:
document.getElementById(div_id).style.display = "none";
Upvotes: 5
Reputation: 2482
function hide_div(div_id) {
$(div_id).hide();
}
...where...
div_id = '#someId';
hide_div(div_id);
Upvotes: 0