1

Right now I have a function that looks like this:

function hidearray() {
    $('#one, #two, #three').hide();
}

I'd like to put those IDs into 1 array, which would look like

var myArray['one', 'two', 'three'];

And then hide that array within my function hidearray(). I thought it would look like this, but I guess I'm on the wrong track (I also know I ignored the # in the statement below)

$(.each(myArray)).hide();

The solution is likely simple, so thank you to all that respond!

7 Answers 7

6

jQuery selectors are just strings, so create a string by joining the array :

$('#' + myArray.join(', #')).hide();

FIDDLE

Sign up to request clarification or add additional context in comments.

2 Comments

+1 I think .join is the most straightforward way to approach this.
Thanks everybody for such a quick rush of comments! This was the shortest solution.
3

I’d use getElementById. Assuming support for Array.map:

var myArray = ['one', 'two', 'three'];

$(myArray.map(document.getElementById, document)).hide();

Comments

1
for(var i = 0; i < myArray.length; i++) {
     $(myArray[i]).hide();
 }

Comments

0

jsFiddle Demo

Use each, pass the array as the first parameter, and the second will be the callback to work with the current item

var arr = [];
arr.push("#one");
arr.push("#two");
arr.push("#three");
$.each(arr,function(){
 $(""+this).hide();
});

9 Comments

@minitech - It's really important to make sure the strings are strings.
@minitech - Because it isn't treated like a string otherwise.
@TravisJ: Oh, right. jQuery and its silly string-objects-aren’t-strings thing.
The proper way to fix it would be to use the built in parameters -> jsfiddle.net/3PX4P/1
I rather like jsfiddle.net/minitech/3PX4P/2, personally. No, don’t actually do that. ;)
|
0

Hide the array ??. I suppose you mean. How to hide element, by putting their id inside an array with jquery

you could do this.

array = ['#id_tiempo_inicio_0', '#id_tiempo_fin_0', '#id_evento']

$.each(array,function(i, v){
   $(v).hide();
});

Comments

0
var myArray['one', 'two', 'three'];
$.each(myArray,function(i,v){
   $('#'+v).hide();
});

Demo --> http://jsfiddle.net/Utg7p/

Comments

-1

This will do the trick,

html

<div id="one">One</div>
<div id="two">Two</div>
<div id="three">Three</div>
<button id="button">Hide</button>

javascript

jQuery(document).ready(function() {
    var mrHide = ['#one', "#two", "#three"];
    jQuery("button#button").click(function() {
        jQuery.each(mrHide, function(index, value) {
            jQuery(value).hide();
        });
    });
});

http://jsfiddle.net/maxja/LUf4y/2/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.