简体   繁体   中英

Removing Attribute hidden from All DOM Elements Except That Whose Index is given Using Javascript Function Not Working

My Function does not work when i call it. When I Query All Elements And loop over them. I cant get any effect on the UI.

I need to add attribute hidden from all .question and remove .hidden from the one whose index is passed to the Js function. classes when i call the function.

Here is the HTML.

<div class="col-md-12 mb-12 question" hidden="hidden" id="D1">
1
</div>
<div class="col-md-12 mb-12 question" hidden="hidden" id="D2">
2
</div>
<div class="col-md-12 mb-12 question" hidden="hidden" id="D3">
3
</div>
<div class="col-md-12 mb-12 question" hidden="hidden">
4
</div>


Calling the lines in the If condition alone without the loop works. What could i not be doing right here.

function hideothersexcept(index){
    var ALLQNS = $('.question');
    for (i = -1; i < ALLQNS.length; i++) {
        if (index == i) {
            $('#' + getid(index)).removeAttr('hidden')
        } else {
            ALLQNS[index].setAttribute("hidden", "hidden");
        }
    }
}
function getid(elm) {
     var ALLQNS = $('.question');
     k = ALLQNS[elm].getAttribute("id");
     return k;
}

Try following code its more clean and succinct then manually looping through all divs and more importantly it works :)

function hideothersexcept(index){                
    $('.question').each(function(elIndex, el){
            if(elIndex == index){
            $(el).removeAttr('hidden');
        }else{
            $(el).attr('hidden', 'hidden');
        }
    });   
}

hideothersexcept(1);

It will hide all other dive except div containing number 2.

NOTE: indexing is zero-based :)

Please let me know if it does not work.

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