user889030 user889030 - 3 days ago 6
HTML Question

add class to span inside a button tag in jquery

am trying to add class to span inside a button tag

so initially i have submit button something like that

<button type="submit" id="sbtn" name="submit" class="btn btn-lg btn-warning"><span id="sid"></span> Submit</button>


next i have click function in which i tried different ways to add class to span but none of them worked , i have commented which not working

$("#sbtn").click(function(e) {
$(this).html(' Loading ...');
// $(this).find('span').addClass('glyphicon glyphicon-refresh glyphicon-refresh-animate');
// $(".btn.btn-lg.btn-warning>span").addClass('glyphicon glyphicon-refresh glyphicon-refresh-animate');
// $("#sid").addClass('glyphicon glyphicon-refresh glyphicon-refresh-animate');
// $("button.btn.btn-lg.btn-warning span").addClass('glyphicon glyphicon-refresh glyphicon-refresh-animate');

});


so any idea how to add class so that i get

<button type="submit" id="sbtn" name="submit" class="btn btn-lg btn-warning"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span> Loading ...</button>

Answer

the problem is that by using

$(this).html('Loading ...'); you delete the span from inside the button, and so...trying to find it and give it a class is useless because it doesn't exist anymore because you change the html of the button

so there are a few solutions for this

1. adding also the spaninside the html()

$("#sbtn").click(function(e) { 
            $(this).html(' <span></span>Loading ...');
       $(this).find('span').addClass('glyphicon glyphicon-refresh glyphicon-refresh-animate');
      
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit" id="sbtn" name="submit" class="btn btn-lg btn-warning">
<span id="sid"></span> Submit</button>

2 . you could add the span together with it's classes and not use addClass . but this is a messy solution

$("#sbtn").click(function(e) { 
            $(this).html('<span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span>Loading ...');

      
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit" id="sbtn" name="submit" class="btn btn-lg btn-warning">
<span id="sid"></span> Submit</button>

Comments