goscamp
goscamp

Reputation: 1106

Take attribute value from where style display is not none

I have few divs:

<div clas="modal-body step step-1" data-step="1" style="display: block;"></div>
<div clas="modal-body step step-2" data-step="2" style="display: none;"></div>
<div clas="modal-body step step-3" data-step="3" style="display: none;"></div>

I would like to get the value of attribute "data-step" where style: display is not none.

Is it possible with JavaScript or JQuery?

Upvotes: 0

Views: 601

Answers (2)

gavgrif
gavgrif

Reputation: 15489

You can use the :visible selector in jQuery. This will create a node list (like the querySelectorAll that will contain only the item /s that is not hidden. Then you can get the data-step value of that element.

let visibleStep =$(".step:visible");
console.log(visibleStep.attr('data-step')); // gives  1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wathever">
  <div class="modal-body step step-1" data-step="1" style="display: block;">A</div>
  <div class="modal-body step step-2" data-step="2" style="display: none;">B</div>
  <div class="modal-body step step-3" data-step="3" style="display: none;">C</div>
</div>

Upvotes: 1

user8094363
user8094363

Reputation:

I just did some sketch on fiddle, try it and let me know if is what you need sir. This is a pure javascript solution.

let nodeList = document.getElementById("wathever").querySelectorAll(".step");
nodeList.forEach(function(div){
   if(div.style.display!="none"){
      //do something
      let dataStep = div.dataset.step;
      console.log(dataStep);
   }
});
<div id="wathever">
  <div class="modal-body step step-1" data-step="1" style="display: block;">A</div>
  <div class="modal-body step step-2" data-step="2" style="display: none;">B</div>
  <div class="modal-body step step-3" data-step="3" style="display: none;">C</div>
</div>

Upvotes: 0

Related Questions