简体   繁体   中英

Javascript “document.getElementById” wildcard loop?

Can wildcards be used with the Javascript "document.getElementById" line?

I have a Vb.net form with 3 div elements ("page1, page2, page3"). What I'm hoping to accomplish is allowing the user to click a button or hyperlink button that will navigate them to the next div ("page#"). Is there a way to do something like the following & loop through each element that has an ID like "page1", "page2", "page3", etc without hard coding?

function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'none')
e.style.display = 'block';
else
e.style.display = 'none';

For what I understand, you are looking for the querySelectorAll function and a for-in loop:

var elements = document.querySelectorAll("[id^='page']");
for(var e in elements){
   // do Stuff - each element get's reached by elements[e]
}

for example:

var elements = document.querySelectorAll("[id^='page']");
for(var e in elements){
   if(elements[e].style.display == 'none')
        elements[e].style.display = 'block';
    else
        elements[e].style.display = 'none';
}

this will catch all elements with an id starting with the word "page" and toggle their visibility

Short answer: no, this is not possible. As Markai has pointed out, it is possible. I still feel like using a class is more appropriate, as this better captures the semantics.

A bit longer answer: perhaps you can give each element a class="page" . Then you can hide all elements with that class and only display the one you're interested in. You can get elements with class 'page' by using document.getElementsByClassName('page') or the more friendly jQuery selector $('.page') .

You could loop the elements. Instead of a toggle, hide all elements except the one you want.

function EnableVisibility(elementName, elementId)
{
    for(i=1;i<4;i++)
    {
        if(i == elementId)
             document.getElementById(elementName + i).style.display = 'block';
        else
             document.getElementById(elementName + i).style.display = 'none';
    }
}

EnableVisibility("page", 2); // This would hide all pages and display page2

If you don't like the hardcoded 4, you could change the for loop with a while and if getElementById returns a null then exit the loop.

I personally like the class idea from Martijn and instead of changing the style directly you add or remove a class ex: class="page visible" class="page hidden"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM