JQuery: How to select the next element named xyz?

I am trying to create a really simple universal switch function in which the switch "switch" has a class .toggle, and then I want it to be the toggle()next element that the class has .toggle-content.

HTML example:

<p>
  <a href="#" class="toggle">Toggle the thing</a>
</p>
<p class="toggle-content hidden">I'm totally hidden right now</p>

So, now I would switch this with:

$(".toggle").click(function() {
  $(this).parent().next('.toggle-content').toggle();
});

The problem is that if the class .toggleis deeper in the DOM, I must continue to stick more parent()depending on how much it is / not.

So, how can I just select the next instance .toggle-contentwithout using a bunch parent()and next()?

+3
source share
2 answers

closest() (docs) parent() (docs).

$(this).closest('p').next('.toggle-content').toggle();

<p>.

(, this, <p>, .)


EDIT: , :

$(this).parentsUntil('> .toggle-content:last').next('.toggle-content').toggle();

parentsUntil() (docs), , .toggle-content. , child-selector (docs).

, .

: http://jsfiddle.net/yCG72/


, filter() (docs).

$(this).parents().filter(function(){
    return $(this).next('.toggle-content').length;
}).first().next('.toggle-content').toggle();

: http://jsfiddle.net/yCG72/1/

+3

.closest() .nextAll():

$(this).closest('p').nextAll('.toggle-content:first').toggle();

.nextAll() , .toggle-content .


"" , , , , , jQuery:

$.fn.nextR = function (selector) {
    var el;
    if (this.children().length) {
        el = this.children().eq(0);
    } else if (this.next().length) {
        el = this.next();
    } else {
        el = this.parent().next();
    }

    if (selector && !el.is(selector) && el.length) {
        el = el.nextR(selector);
    }
    return el;
};

:

$(this).nextR('.toggle-content').toggle();

. : http://jsfiddle.net/4uVM5/

0

Source: https://habr.com/ru/post/1789252/


All Articles