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

141
August 27, 2018, at 02:00 AM

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;
}
Answer 1

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.

Rent Charter Buses Company
READ ALSO
Access CSS variable from javascript [duplicate]

Access CSS variable from javascript [duplicate]

This question already has an answer here:

158
css .not(this) element according to it&#39;s index

css .not(this) element according to it's index

I'm trying to create an accordion sliderSo far I've managed to:

125
JQuery window.location.assign method doesn&#39;t work

JQuery window.location.assign method doesn't work

I've struggled with this problem for two daysI googled it and see some similar cases

147
Microsoft Dynamics CRM C# Plugin to use Jquery and Ajax

Microsoft Dynamics CRM C# Plugin to use Jquery and Ajax

Below image shows my Jquery with Ajax code

133