Home > Enterprise >  JavaScript loop throught and hide all divs except one
JavaScript loop throught and hide all divs except one

Time:07-10

I have a big list of getElementsById that looks like this:

let ahSummerCamps = document.getElementById("aH-summerCamps");
let ahTrekking = document.getElementById("aH-trekking");
let bpLongDistanceHiking = document.getElementById("bp-longDistanceHiking");
let bpThruHiking = document.getElementById("bp-thruHiking");
let cOceanCruising = document.getElementById("c-oceanCruising");
let cRiverCruising = document.getElementById("c-riverCruising");
let eRecreationsEvent = document.getElementById("e-recreationsEvent");
let eSportsEvent = document.getElementById("e-sportsEvents");
let phEscortedTours = document.getElementById("ph-escortedTours");
let phIndependentTours = document.getElementById("ph-independentTours");
let sPhotographicSafari = document.getElementById("s-photographicSafari");
let sCyclingSafari = document.getElementById("s-cyclingSafari");
let sAsBackcountrySkiing = document.getElementById("sAs-backcountrySkiing");
let sAsDownhillSkiing = document.getElementById("sAs-downhillSkiing");
let vChildcare = document.getElementById("v-childcare");
let vConservationAndEnvironment = document.getElementById("v-conservationAndEnvironment");

I won't go into details, is there any way that I can loop throught all of them and for example hide all except bpLongDistanceHiking and bpThruHiking .

I had this function but that is not good way for sure:

function hideAllExceptbP() {
ahSummerCamps.style.display = "none";
ahTrekking.style.display = "none";
/* ... and for all of them like this except bpLongDistanceHiking and bpThruHiking  */
}

So on that way I need function for every element like:

function hideAllExceptaH() {
/* ...   10 lines */

function hideAllExceptC() {
/* ...   10 lines */

function hideAllExceptE() {
/* ...   10 lines */

Function

function choice() {
backpacking.addEventListener("click", () => {
    hideBackpacking();
    hideSafari();
    hidePackageHoliday();
    showBackpackingOptions();
    console.log("Backpacking");
});

So as you can see from html I have 8 divs at start, and when user click on backpacking for example function should hide all divs except bpLongDistanceHiking and bpThruHiking

Full code calling function:

HTML:

    <div >

    <!--main divs-->
    <div style="background-color: #4cc9f0"  id="adventureHolidays"><p>Adventure Holidays</p></div>
    <div style="background-color: #4895ef"  id="backpacking"><p>Backpacking</p></div>
    <div style="background-color: #4361ee"  id="cruiseHolidays"><p>Cruise Holidays</p></div>
    <div style="background-color: #4361ee"  id="eventTravel"><p>Event Travel</p>
    </div>
    <div style="background-color: #3a0ca3"  id="packageHoliday"><p>Package Holiday</p></div>
    <div style="background-color: #480ca8"  id="safari"><p>Safari</p></div>
    <div style="background-color: #560bad"  id="skiingAndSnowboarding"><p>Skiing and Snowboarding</p>
    </div>
    <div style="background-color: #7209b7"  id="volunteering"><p>Volunteering</p></div>

    <!--end on main divs-->

    <!--sub divs-->

    <div style="background-color: #4cc9f0"  id="aH-summerCamps"><p>Summer camps</p></div>
    <div style="background-color: #4895ef"  id="aH-trekking"><p>Trekking</p></div>
    <div style="background-color: #4361ee"  id="bP-longDistanceHiking"><p>Long Distance Hiking</p></div>
    <div style="background-color: #4361ee"  id="bP-thruHiking"><p>Thru Hiking</p></div>
    <div style="background-color: #3a0ca3"  id="c-oceanCruising"><p>Ocean Cruising</p></div>
    <div style="background-color: #480ca8"  id="c-riverCruising"><p>River Cruising</p></div>
    <div style="background-color: #560bad"  id="e-recreationsEvent"><p>Recreations Events</p></div>
    <div style="background-color: #7209b7"  id="e-sportsEvents"><p>Sports events</p></div>
    <div style="background-color: #4cc9f0"  id="pH-escortedTours"><p>Escorted Tours</p></div>
    <div style="background-color: #4895ef"  id="pH-independentTours"><p>Independent Tours</p></div>
    <div style="background-color: #4361ee"  id="s-photographicSafari"><p>Photographic Safari</p></div>
    <div style="background-color: #4895ef"  id="s-cyclingSafari"><p>Cycling Safari</p></div>
    <div style="background-color: #3a0ca3"  id="sAs-backcountrySkiing"><p>Backcountry skiing</p></div>
    <div style="background-color: #560bad"  id="sAs-downhillSkiing"><p>Downhill skiing</p></div>
    <div style="background-color: #4361ee"  id="v-childcare"><p>Childcare</p></div>
    <div style="background-color: #4895ef"  id="v-conservationAndEnvironment"><p>Conservation And
        Environment</p></div>
</div>
<script type="text/javascript" th:src="@{/js/index.js}"></script>

js:

    let adventureHolidays = document.getElementById("adventureHolidays");
let backpacking = document.getElementById("backpacking");
let cruiseHolidays = document.getElementById("cruiseHolidays");
let eventTravel = document.getElementById("eventTravel");
let packageHoliday = document.getElementById("packageHoliday");
let safari = document.getElementById("safari");
let skiingAndSnowboarding = document.getElementById("skiingAndSnowboarding");
let volunteering = document.getElementById("volunteering");
/*End of inserting main variables*/

/*sub variables*/

let ahSummerCamps = document.getElementById("aH-summerCamps");
let ahTrekking = document.getElementById("aH-trekking");
let bPLongDistanceHiking = document.getElementById("bP-longDistanceHiking");
let bPThruHiking = document.getElementById("bP-thruHiking");
let cOceanCruising = document.getElementById("c-oceanCruising");
let cRiverCruising = document.getElementById("c-riverCruising");
let eRecreationsEvent = document.getElementById("e-recreationsEvent");
let eSportsEvent = document.getElementById("e-sportsEvents");
let phEscortedTours = document.getElementById("ph-escortedTours");
let phIndependentTours = document.getElementById("ph-independentTours");
let sPhotographicSafari = document.getElementById("s-photographicSafari");
let sCyclingSafari = document.getElementById("s-cyclingSafari");
let sAsBackcountrySkiing = document.getElementById("sAs-backcountrySkiing");
let sAsDownhillSkiing = document.getElementById("sAs-downhillSkiing");
let vChildcare = document.getElementById("v-childcare");
let vConservationAndEnvironment = document.getElementById("v-conservationAndEnvironment");

/*end of subs variables*/

const divs = ["adventureHolidays", "backpacking", "cruiseHolidays", "eventTravel", "packageHoliday", "safari", "skiingAndSnowboarding", "volunteering", "aH-summerCamps", "aH-trekking", "bP-longDistanceHiking", "bP-thruHiking", "c-oceanCruising", "c-riverCruising", "e-recreationsEvent", "e-sportsEvents", "ph-escortedTours", "ph-independentTours", "s-photographicSafari", "s-cyclingSafari", "sAs-backcountrySkiing", "v-conservationAndEnvironment", "sAs-downhillSkiing", "v-childcare"]
    .map(id => document.getElementById(id)); // gives you an array of those elements

function hideAllDivsExcept(id) {
    for (const div of divs) div.hidden = !div.id === id;
}


window.onload = function () {
    choice();
};


/* start of function choice for user clicks*/

function choice() {
    backpacking.addEventListener("click", () => {
        hideAllDivsExcept('adventureHolidays');
        console.log("Backpacking");
    })
}

CSS:

 * {
    box-sizing: border-box;
}

/* Create three equal columns that floats next to each other */
.column {
    float: left;
    width: 33.33%;
    padding: 10px;
}

/* Clear floats after the columns */
.row:after {
    content: "";
    /*
    display: table;
    */
    clear: both;
}

I'm getting:

index.js:38 Uncaught TypeError: Cannot read properties of null (reading 'id')
at hideAllDivsExcept (index.js:38:47)
at HTMLDivElement.<anonymous> (index.js:51:9)

And that is this

    function hideAllDivsExcept(id) {
   this > for (const div of divs) div.hidden = !div.id === id;
}

CodePudding user response:

Add an id to your main div with class 'row', e.x. daDiv then iterate and perform whatever you want checking id attribute of each one

$('#daDiv').children('div').each(function () {
  if ($(this).attr('id') !== 'bP-longDistanceHiking' && $(this).attr('id') !== 'bP-thruHiking') {
    $(this).hide();
  }
});

CodePen

Example

UPDATE

You can even make a function

function hideExcept(arr) {

  $('#daDiv').children('div').each(function () {
    if (!arr.includes($(this).attr('id')))
      $(this).hide();
  });
}

hideExcept(['bP-longDistanceHiking', 'bP-thruHiking']); // hide all except bP-longDistanceHiking and bP-thruHiking

CodePudding user response:

I'd use jquery for this

 $("#div1").show()
 $("#div1").hide()
  • Related