Quantcast
Channel: Javascript: select multiple div ID's - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Answer by Jamie Cockrill for Javascript: select multiple div ID's

$
0
0

Here is an answer where the number of anchor (<a>) tags is derived from the number of div elements in your html body. No jQuery here either.

If you give <div class="buttons"> an id and each of the inner_divdivs a common class, you can then select all of the inner_div elements by class name and generate an anchor tag for them.

You can then do away with the logic of which div is visible by just setting them all to style="display: none;" and then only setting style="display: block;" on the element matching the ID of the one you clicked on.

    var divs = document.getElementsByClassName('invizdiv');    /*      This bit sets up your anchor tags dynamically depending on     how many divs you have with the class 'invizdiv'    */    for (var i = 0; i < divs.length; i++) {        var listDivId = divs[i].id.slice();        var newAnchor = document.createElement('a');        newAnchor.innerHTML = listDivId;        newAnchor.className = "buttons";        newAnchor.href = '#';        newAnchor.setAttribute('targetdiv', listDivId);        // console.log(listDivId);        newAnchor.addEventListener('click', function(elem, event) {            // console.log(elem);            // console.log(event);            divVisibility(elem.target.getAttribute('targetdiv'));        });        document.getElementById('button_list').appendChild(newAnchor);    }    // here onwards is unchanged    var visibleDivId = null;    function divVisibility(divId) {        var div;        for (var i = 0; i < divs.length; i++) {            div = divs[i];            div.style.display = "none";        }        div = document.getElementById(divId);        div.style.display = "block";    }
.buttons a {  font-size: 16px;}.buttons a:hover {  cursor: pointer;  font-size: 16px;}
<div class="main_div"><div id="button_list" class="buttons"><!-- We'll dynamically add here later --></div><div class="inner_div"><div id="Div1" class="invizdiv">I'm Div One</div><div id="Div2" class="invizdiv" style="display: none;">I'm Div Two</div><div id="Div3" class="invizdiv" style="display: none;">I'm Div Three</div><div id="Div4" class="invizdiv" style="display: none;">I'm Div Four</div></div></div>

Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>