marry
marry

Reputation: 173

how to assign css to a nested img in jquery

How do i access my img to assign it a width? my img is nested in an anchor tag and divs

<div id="Banner">
 <div id="setting"></div>
<div>
<a>
<img src="test"> // i want the width to come here
</a>
</div>
</div>

this is what i tried

function fixBannerWidth() {
           var container = $($('#Banner').children('div'));
           container.css('position', 'relative');
            container.css('height', 'auto');
            container.css('width', '100%');
            $('#Banner img').attr('height', null);
            $('#Banner img').attr('width', null);
            $('#Banner img').addClass('center-block');
        }

but the width gets added to the div as follows and the img doesnt get bigger only the div does. so how do i assign the width to the img class

<div id="Banner">
 <div id="setting"></div>
<div style="width:100%"> // the width gets added here
<a>
<img src="test"> // i want the width to come here
</a>
</div>
</div>

Upvotes: 1

Views: 61

Answers (2)

Deepak
Deepak

Reputation: 55

you can directly access the img like this

var container = $('#Banner a img');

Upvotes: 3

ciekals11
ciekals11

Reputation: 2155

You can use something like this:

$(document).ready(function(){
  fixBannerWidth();
});

function fixBannerWidth() {
  var img = $('#banner div img');
  var container = img.parent().parent();
  

  container.css('position', 'relative');
  container.css('height', 'auto');
  container.css('width', '100%');

  img.css('height', 'auto');
  img.css('width', '100%');
  img.addClass('center-block');
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<div id="banner">
  <div id="setting"></div>
  <div>
    <a>
      <img src="data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7">
    </a>
  </div>
</div>

Upvotes: 0

Related Questions