Snippet: seleccionar el siguiente elemento con jQuery sin importar la estructura DOM

13 Oct 2016

Objetivo

Necesitamos seleccionar el siguiente elemento en el DOM que cumpla con nuestro criterio de selección, independientemente de si es un hijo/descendente, un hermano, o si está a muchos nodos de distancia. Solo necesitamos que nuestro plugin localice y seleccione nuestro selector a partir de un punto del DOM concreto y hacia abajo.

Cuándo puede ser útil

  • Tenemos un elemento DOM y queremos seleccionar a partir de él, el siguiente que cumpla una condición dada.
  • Utilizamos código de terceros donde apenas tenemos selectores con los que trabajar.

Soporte y dependencias

El código

/**
 * nextThrough
 * jQuery plugin to find the next element that matches a selector,
 * whatever the DOM structure.
 *
 * @param   {string}    selector    A jQuery/CSS selector to find from a given jQuery object
 * @return  {object}                The new element found
 */
( function ( $ ) {
    'use strict';
    $.fn.nextThrough = function( selector ) {
        // Our reference will be the last element of the current set
        var $reference = $( this ).last(),
            // Add the reference element to the set the elements that match the selector
            $set = $( selector ).add( $reference ),
            // Find the reference position to the set
            $pos = $set.index( $reference );
 
        // Return an empty set if it is the last one
        if ( $set.length === $pos ) {
            return $();
        }
 
        // Return the next element to our reference
        return $set.eq( $pos + 1 );
    };
} ( jQuery ) );

Ejemplo de uso

// By simple class
$( '.user-comment' ).nextThrough( '.pending' ).addClass( 'bg-red' );
 
// More complex CSS selector
$( '.user-data' ).nextThrough( 'td:empty:not(.highligthed)' ).hide();
Más:

Aún no tenemos debug!
Ningún marciano se ha comunicado.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *