Home > database >  adding html inside button when button has active class
adding html inside button when button has active class

Time:09-08

I am trying to run some jQuery to check if certain buttons have the class .active, to then add a check mark inside those buttons.

I can change the HTML for all buttons if one of them has the active class but can't seem to figure for each one.

This is the bootstrap button with the toggle:

<button  data-bs-toggle="button">
   Texte bouton
</button>

and here is the JavaScript that doesn't work:

if ($('.btn-vert').hasClass('active')) {
    $(this).append('<span ><i ></i></span>');
} 

CodePudding user response:

You need to loop trough your buttons.
This adds a check mark to all buttons with the class active

I am trying to run some JavaScript to check if certain buttons have the class .active, to then add a check mark inside those buttons.

This succeeds in that

$('.btn-vert').each(function(i, button) {
    if ($(button).hasClass('active')) {
        $(button).append('<span ><i ></i></span>');
    } 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE 4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<button  data-bs-toggle="button">
   Texte bouton
</button>
<button  data-bs-toggle="button">
   Texte bouton
</button>
<button  data-bs-toggle="button">
   Texte bouton
</button>

  • Related