Ell
Ell

Reputation: 51

Trying to select single elements within a class. Not working with "jQuery(this).next"

I am trying to select only one element with the class name postcode-overlay-not using jQuery(this).next() which has worked for me in similar situations in the past. This time it does not seem to be working. I have tried using .prev() and this also has not worked.

Any help appreciated!

jQuery(".help-container .delivery-options__option .postcode-restrictions-not").click(function() {
    jQuery(this).next(".help-container .delivery-options__option .postcode-overlay-not").fadeIn("slow");
});

jQuery(".help-container .delivery-options__option .postcode-overlay-not .closing-x").click(function() {
    /*jQuery(".help-container .delivery-options__option .postcode-overlay").css("display", "none");*/
    jQuery(this).next(".help-container .delivery-options__option .postcode-overlay-not").fadeOut("slow");
}); 

Upvotes: 0

Views: 73

Answers (1)

fdomn-m
fdomn-m

Reputation: 28621

.next() gets just the very next DOM node, then compares it with the class(es) you've specified.

In your case, you've specified multiple, hierarchical classes which will never match a single node.

As you've not provided the HTML structure, here are some ideas to replace the .next():

jQuery(".help-container .delivery-options__option .postcode-restrictions-not").click(function() {

    // remove (this) and just get from the top again
    // will likely match multiple
    jQuery(".help-container .delivery-options__option .postcode-overlay-not").fadeIn("slow");

    // Use (this).next, assuming the next is *exactly* as specified
    // unlikely, but depends
    jQuery(this).next(".postcode-overlay-not").fadeIn("slow");

    // Use nextAll().first()
    // will work if they are siblings
    jQuery(this).nextAll(".postcode-overlay-not").first().fadeIn("slow");

    // Use up to shared parent, then down
    // most likely to work, but depends on where others are
    jQuery(this).closest(".delivery-options__option").find(".postcode-overlay-not").fadeIn("slow");

});

Upvotes: 3

Related Questions