简体   繁体   中英

remove and add class with javascript on page load issue

When i add or remove a class with javascript then reload the page ..

it wont work

I tried this code, and put it in on the header

<script>
    $(document).ready(function() {
  $('.boxAdRight').removeClass('boxAdRight').addClass('active');
});
</script>

and this is my HTML I want to remove the class boxAdRight and change it with .active class

 <div class="panel-body"> <div class="tab-content"> <div class="tab-pane fade in active" id="data"> <div class="getData"> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="servers"> <ul> <li class="active" id="s_0"onclick="getServer(this.id,0);"> <i class="fa fa-video-camera"></i> server1 </li> </ul> </div> </div> <div class="col-md-3 col-sm-4 col-xs-12 fRight"> <div class="episodes boxAdRight"> <h2>episodes</h2> <ul> <li> <a href="http://localhost/wordpress/newarticle13/"> episode 1</a> </li> <li class="active"><a href="http://localhost/wordpress/newarticle13/"> episode 2</a> </li> </ul> </div> </div> <div class="col-md-9 col-sm-8 col-xs-12 fRight"> <div class="boxVideos"> <div class="getCode"><iframe src="https://*******" scrolling="no" frameborder="0" width="700" height="430" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe> </div> </div> </div> </div> </div> </div> </div> </div> 

thank you

As a first observation I would like to mention the fact that JQuery's removeClass function returns one or more space separated class names that should be removed. As a consequence, you should not apply addClass over the result of removeClass.

There might be other issues also in your code though...

Replace your .boxAdRight class with .episodes class and it'll work as you want.

  <script>
        $(document).ready(function() {
            $(".episodes").removeClass("boxAdRight").addClass("active");
       });
    </script>

I believe that the order of the method calls should be

$('.boxAdRight').addClass('active').removeClass('boxAdRight');    

In the original example $('.boxAdRight').removeClass('boxAdRight').addClass('active'); the selector .boxAdRight is being used, but then that class is being removed with .removeClass('boxAdRight') , so .addClass('active') is being called on a selector with no matching elements.

get it like that will solve it

$('.episodes').addClass('active').removeClass('boxAdRight');

in normal case yours too must work ?

You can also simplify this code by replacing of class instead of removing it.

$('.boxAdRight').className = 'active';

how to replace class HTML name with javascript

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