-2

I am trying something like this. But it is not helping at all. I double checked that class name is correct. Any help will be appreciated.

<script>
$(window).bind("load", function() {
for(var i=0, len=document.getElementsByClassName('xd_top_box').length;i<len;i++){
   document.getElementsByClassName('xd_top_box').style.display='inline-block';
}
});
</script>

I was trying to use jquery but then mixed it up with javascript. jQuery is shorter and much better I think.

3 Answers3

2

Firstly you have an odd mix of JS and jQuery. If you're loading jQuery you may as well use it. Secondly, bind() has been deprecated. You should use on('load', fn) instead.

Lastly the issue is because getElementsByClassName returns an array like object which you need to iterate over before updating the style.display of each individual element.

Try this:

$(window).on('load', function() {
  $('.xd_top_box').css('display', 'inline-block');
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

Like Rory mentioned, you want to use $.on() instead of $.bind() but if you wanted to use your original JS, you just need to reference the index of each element returned by getElementsByClassName

.xd_top_box {
  background: black;
  color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
  $(window).on("load", function() {
    var box = document.getElementsByClassName("xd_top_box");
    for (var i = 0; i < box.length; i++) {
      box[i].style.display = "inline-block";
    }
  });
</script>
<div class="xd_top_box">asdf</div>
Michael Coker
  • 52,626
  • 5
  • 64
  • 64
0

You can use the $(document).ready() method:

(function () {
    $(document).ready(function(){
        $('.xd_top_box').css('display', 'inline-block');
    });
})(jQuery);

And include a self closure to keep everything contained and variables from leaking out into other functions.

Jacob King
  • 196
  • 2
  • 9