Using jQuery I'd like to be able to add a new class to the container div (.figure-left) only if the image within it has a class of .landscape
I'm using a great script I found on CSSnewbie.com that uses the Alt tag of an image as a caption - very useful when the CMS I'm using doesn't support image captioning.
I have the basic script working and I've styled the CSS so the layout won't break if Javascript is turned off. The bit I can't get to work is my 'addition' :)
I've added the ' if ' part to the script below, which partly works . It adds a class called 'NEW-CLASS' to the containing div (.figure-left).
Unfortunately it adds .NEW-CLASS to every div (.figure-left). It seems to ignore the 'if' bit? I only want a class adding to div (.figure-left) if there's a image inside with a class of .landscape
HTML:
<div class="figure-left">
<img alt="This is the caption" class="caption left landscape"
height="413" src="/img/resources/photo.jpg"
width="620"><p class="caption">This is the caption</p>
</div>
Script:
$(document).ready(function() {
$("img.caption.left").each(function() {
$(this).wrap('<div class="figure-left"></div>')
.after('<p class="caption">'+$(this).attr("title")+'</p>')
.removeAttr('title');
if ($('img').hasClass('landscape')) {
$('.figure-left').addClass('NEW-CLASS');}
});
Really appreciate some help, been scratching my head all morning! :)
I'm only using .NEW-CLASS for this example.
I'd suggest skipping the if
entirely, and selecting the relevant images (with the class-name you're testing for), and then finding the closest .figure-left
and adding the class:
$('img.landscape').closest('.figure-left').addClass('NEW-CLASS');
However the problem with your own code was that you were selecting all the .figure-left
elements inside of the if
, so, instead, you should use:
if ($(this).hasClass('landscape')) {
$(this).closest('.figure-left').addClass('NEW-CLASS');
}
In this example $(this)
refers to the current element (the img
) and tests whether it has the landscape
class-name; if it does then the jQuery finds the closest .figure-left
element of the ancestors of that img
element and adds the NEW-CLASS
class-name.
References:
addClass()
. closest()
. hasClass()
.
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.