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();
}
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";
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With