简体   繁体   中英

Add class to divs which contains an image of a certain width

Hi let me start with the codes.

<div class="nyhet"> <img src="#" width="785" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="390" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="785" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="390" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="785" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="390" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="785" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="390" class="attachement-full" /></div>

Ok, so basically what I want is that the divs with an image that is 785 should get a class named large added to it, and the divs with an image that is 390 should get a class named small.

So it should look like this.

<div class="nyhet large"> <img src="#" width="785" class="attachement-full" /></div>
<div class="nyhet small"> <img src="#" width="390" class="attachement-full" /></div>
<div class="nyhet large"> <img src="#" width="785" class="attachement-full" /></div>

and so on. This is what I've tried to so far.

$(document).ready(function(){
  var x = $(".nyhet").length;
  for (var i=0; i<x;i++){
    n = $(".attachement-full:eq(i)").attr("width");
    if (n<785) {
      $(".nyhet:eq(i)").addClass("small");
    } else {
      $(".nyhet:eq(i)").addClass("large");
    }
  }
});

I chose to use .attr instead of .width because the images probably won't be finished loading when the script runs.

Any help would be appriciated!

Based on your code snippet I couldn't tell if you wanted to set images with width 786 as larget so heres a way to do it for ranges:

$(".nyhet img").each(function() {
    var $par = $(this).parent(".nyhet");
    if(this.offsetWidth >= 785) {
        $par.addClass("large");
    } else {
        $par.addClass("small");
    }
})

You can just use one selector:

$("img[width=785]").parent(".nyhet").addClass("large");
$("img[width=390]").parent(".nyhet").addClass("small");

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