Is there an alternative to '#' + div_id?

Is there a better way to write the following function?

Having '#' + div_id just looks wrong.

 function hide_div(div_id) { $('#' + div_id).hide(); } 
+6
source share
6 answers

The short answer is no. A slightly longer and more hacky answer: create a function with a one-letter long name that takes the element identifier and returns getElementById on it, and then wrap this in your jQuery $() , for example:

 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 

These are three characters. Is it worth it? Are these three characters really that important to you? You already save a lot without using document.getElementById (id) (27 characters).

+4
source

If you somehow oppose string concatenation, you can do this instead:

 $(document.getElementById(div_id)).hide(); 

You can also pass a full selector, for example:

 hide_div("#divId"); 

If you want to do this in javascript in vanilla, you can do this:

 document.getElementById(div_id).style.display = "none"; 
+5
source

Several alternative ways:

 $(['#', div_id].join('')).hide(); $('#'.concat(div_id)).hide(); 

Also, @Thomas inspired me on this alternative solution:

When you call your function, use:

 $.proxy( hide_div, $('#' + div_id) ); // Then, you can do this: function hide_div() { this.hide(); } 

This may allow you to better reuse it. Or not.

+2
source
 function hide_div(div_id) { $(div_id).hide(); } 

... where ...

 div_id = '#someId'; hide_div(div_id); 
0
source

Depending on the use case, you can pass an object instead of id:

 $('#someobject').click(function(){ hideDiv(this); }); 
0
source

No, you cannot shorten it anymore. An alternative to # + div_id would be:

 $('[id="'+div_id+'"]') 

This query works with the attribute selector []. Not shorter, not cleaner, though slower, but an alternative anyway

-5
source

Source: https://habr.com/ru/post/918152/


All Articles