Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there an alternative to '#' + div_id?

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();
}
like image 944
filype Avatar asked Jun 15 '12 07:06

filype


2 Answers

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";
like image 144
Peter Olson Avatar answered Sep 20 '22 02:09

Peter Olson


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).

like image 43
Ashley Strout Avatar answered Sep 23 '22 02:09

Ashley Strout