Domanda

How do I test if the next element is certain type - e.g. I want to test if the next element following an image, is also an image. If so, then I want to add a class to that element

e.g. if this was the case then it would trigger true and add a class to the first image...

<p></p>
<img />
<img />
<p></p>

However, in this case then it would trigger false, and nothing would happen...

<p></p>
<img />
<p></p>
È stato utile?

Soluzione

You can use the .is() method of jQuery to do that:

$("#yourimage").next().is("img");

So to add a class like you describe:

var yourimage = $("#yourimage");

if (yourimage.next().is("img")){
   yourimage.addClass("yourExtraClass");
}

Altri suggerimenti

You can use .next() [docs] together with .filter() [docs]:

$('img').filter(function() {
    return $(this).next('img').length === 1;
}).addClass('someClass');

You can also use the next adjacent selector [docs] with .prev() [docs]:

$('img + img').prev().addClass('someClass');
var nextImage = $(this).next('img');

The next method accepts the standard jQuery selectors.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top