0

I have this:

  <div id="myid1">Text 1</div>
  <div id="myid2">Text 2</div>
  <div id="myid3">Text 3</div>

and I would hide all these elements by default. Then when I click on a link, I would like show all them at once. I looked for some solution in Javascript but it seem is not possible to declare multiple ID when using document.getElementById.

Precision: I seen many solution who suggest to use class instead ID. The problem is I work with an external application integrated in my site and I have access partially to html, but I can set javascript code inside a dedicated JS file.

2
  • do you have a option to wrap above code within an parent DIV? if that's the case then you can control your parent DIV within your JS File. Commented Apr 26, 2014 at 21:47
  • no unfortunately. The code is a bit messy and the parent div include some others element which don't need to be show/hide Commented Apr 26, 2014 at 21:53

3 Answers 3

2

You could create a function that retrieves several elements by their id, and simply iterate over that collection of elements to hide or show them:

function getElementsByIds(idArray) {
    // initialise an array (over which we'll iterate, later)
    var elements = [];

    // if no arguments have been passed in, we quit here:
    if (!arguments) {
        return false;
    }
    else {
        /* we're running a basic check to see if the first passed-argument
           is an array; if it is, we use it: */
        if (Object.prototype.toString.call(arguments[0]) === '[object Array]') {
            idArray = idArray;
        }
        /* if a string has been passed-in (rather than an array), we
           make an array of those strings: */
        else if ('string' === typeof arguments[0]) {
            idArray = [].slice.call(arguments);
        }

        // here we iterate over the array:
        for (var i = 0, len = idArray.length; i < len; i++) {

            // we test to see if we can retrieve an element by the id:
            if (document.getElementById(idArray[i])) {
                /* if we can, we add that found element to the array
                   we initialised earlier: */
                elements.push(document.getElementById(idArray[i]));
            }
        }
    }
    // returning the elements:
    return elements;
}

// here we toggle the display of the elements (between 'none' and 'block':
function toggle (elems) {
    // iterating over each element in the passed-in array:
    for (var i = 0, len = elems.length; i < len; i++) {
        /* if the current display is (exactly) 'none', we change to 'block'
           otherwise we change it to 'none': */
        elems[i].style.display = elems[i].style.display === 'none' ? 'block' : 'none';
    }
}

function hide (nodes) {
    // iterating over the passed-in array of nodes
    for (var i = 0, len = nodes.length; i < len; i++) {
        // setting each of their display properties to 'none':
        nodes[i].style.display = 'none';
    }
}

// getting the elements:
var relevantElements = getElementsByIds('myid1','myid2','myid3'),
    toggleButton = document.getElementById('buttonThatTogglesVisibilityId');

// binding the click-handling functionality of the button:
toggleButton.onclick = function(){
    toggle (relevantElements);
};

// initially hiding the elements:
hide (relevantElements);

JS Fiddle demo.

References:

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

2 Comments

this could work but how to do for hide all text by default and show them only when the button is clicked ? I tried to play by inverting none/block in your Fiddle but without success (sorry I'm a poor newbie)
I tested and that work on your fiddle but is not working at my side. Text is not hidden and when I click on button I'm redirected to another page of my site. I think I have some conflict somewhere. I must investigate.
0

Three options (at least):

1) Wrap them all in a parent container if this is an option. Then you can just target that, rather than the individual elements.

document.getElementById('#my_container').style.display = 'block';

2) Use a library like jQuery to target multiple IDs:

$('#myid1, #myid2, #myid3').show();

3) Use some ECMA5 magic, but it won't work in old browsers.

[].forEach.call(document.querySelectorAll('#myid1, #myid2, #myid3'), function(el) {
    el.style.display = 'block'; //or whatever
});

3 Comments

by admitting I use your option2 (I don't know if I can use Jquery I must test), how will look the link code ?
$('show-link-button').click(function(){ $('#myid1, #myid2, #myid3').show();} )
I don't see how to use this code inside my html link
0

If id="myid< increment-number >" then you can select these elements very easily.

Below code will select all elements that START WITH "myid".

$("div[id^='myid']").each(function (i, el) {
    //do what ever you want here
}

See jquery doc http://api.jquery.com/attribute-contains-selector/

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.