简体   繁体   中英

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?

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> 

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> 

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