简体   繁体   中英

JQuery Compare Class of List Items

Using JQuery I want to check that each list item has the css class Complete . If so, i want to display a button, if not I want to keep the button hidden.

The classes are currently inserted dynamically using PHP when the page loads.

My code so far is;

<button id="steps-complete" hidden>Download Now</button>

<ul class="wb-steps">
    <li class="<?php echo $class ?>">Step 1</li>
    <li class="<?php echo $class ?>">Step 2</li>
    <li class="<?php echo $class ?>">Step 3</li>
</ul>

<script>
jQuery( document ).ready(function() {
    var steps = [];
    jQuery( ".wb-steps li" ).each(function( index ) {
        // successfully displays complete for each list item
        console.log( index + ": " + jQuery( this ).attr('class') );
        // if all stepa have 'complete' show button
        $("#steps-complete").show();
    });
});
</script>

You have the $class variable, and its value is set as the class of all list items.

Since you are using PHP to render the page, you can use the same variable to test if the button should be shown or not. So you wouldn't need jQuery in this case, you can just remove that part.

Here's what it would look like:

<?php
if (strpos($class, 'Completed') !== false) {
?>
<button id="steps-complete" hidden>Download Now</button>
<?php
}
?>

This works in your case because you set the same class to all items.

Hope this helps.

You can simply count the elements to see if all of them have the complete class:

jQuery(document).ready(function() {
    var $steps = $(".wb-steps li");
    var show = $steps.length === $steps.filter('.complete').length;

    $("#steps-complete")
        .toggle(show)
        .get(0)
        .toggleAttribute('hidden', show);
});

i've made a function to check of the children of the wb-steps have a class named john, if not then we show the steps complete

 jQuery( document ).ready(function() { if($(".wb-steps").children().not('.john').length = 0){ console.log("there was a div found with a class named john"); }else{ $("#steps-complete").show(); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="steps-complete" hidden>Download Now</button> <ul class="wb-steps"> <li class="<?php echo $class?>">Step 1</li> <li class="<?php echo $class?>">Step 2</li> <li class="<?php echo $class?>">Step 3</li> </ul>

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