Home > Net >  Jquery set each selected div height equal to its width
Jquery set each selected div height equal to its width

Time:10-19

I need to set each selected div height equal to its width but this code will not work for me :

<div class="row"><div class="col-md-4 squ"></div><div class="col-md-8"></div></div>
<div class="row"><div class="col-md-10"></div><div class="col-md-2 squ"></div></div>
<script>
$( document ).ready(function() {
    $('div.squ').height($(this).width());
});
</script>

CodePudding user response:

Problem is that $(this) does not refer to the div but the document in your case, so you can do it like:

$(document).ready(function() {
  $('div.squ').height(function() {
    return $(this).width();
  });
});

Demo

Show code snippet

$(document).ready(function() {
  $('div.squ').height(function() {
    return $(this).width();
  });
});
.row div {
  border: 1px solid black;
  display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
  <div class="col-md-4 squ">tester</div>
  <div class="col-md-8">t</div>
</div>
<div class="row">
  <div class="col-md-10">t</div>
  <div class="col-md-2 squ">test</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

$(document).ready(function() {
  $('div.squ').height(function() {
    return $(this).width();
  });
});
  • Related