Philip Kirkbride
Philip Kirkbride

Reputation: 22899

Select by next instance of class with jQuery

I'm looking to convert a function that selects by id to select the next instance of a given class.

Here is the code.

function swap3(oldDivId, newDivId) {
var oldDiv = document.getElementById(oldDivId);
var newDiv = document.getElementById(newDivId);
oldDiv.style.display = "none";
newDiv.style.display = "block";
}

Upvotes: 5

Views: 5894

Answers (3)

Erick Petrucelli
Erick Petrucelli

Reputation: 14932

Suppose you have this HTML:

<div id="test"></div>
<img>
<br>
<div></div>
<input>
<div class="abc">Found it</div>
<div class="cdf"></div>

Updated at 2021

The original answer is quite old now. Since the original question have the jQuery tag, the answer keeps valid and usable. But for those coming here with the hope to see an updated JavaScript code with no dependency on jQuery, take a look on how querySelector is a awesome nowadays:

const next = document.querySelector('#test ~ .abc')
next.textContent = 'Yeah, you found it!'

So the secret is to use the general sibling combinator that matches all iterations of the second element, but with querySelector that returns only the first match.

Original answer

So you select the first div by id:

var some = $("#test");

Then you want to find the next div with the class abc:

var next = some.nextAll("div.abc");

Suppose you want a variable as the className:

var x = "abc";
var next = some.nextAll("div." + x);

Upvotes: 5

Joe
Joe

Reputation: 15812

Select by ID in jQuery:

$('#class_name')

Select by class in jQuery:

$('.class_name')

Get the next item in jQuery:

$('.class_name').next('.class_name')

Using this, you can do something like

// Something to remember the current element
var currentElement = false;

function getNext(className)
{
    // First time, there will be no current element
    if (!currentElement)
    {
        currentElement = $('.' + className);
        return currentElement;
    }

    // Other times...
    currentElement = $(currentElement).next('.' + className);
    return currentElement;

Upvotes: 0

Joe
Joe

Reputation: 82654

If I understand your question:

function nextItem(className) {
    return $('#ID').closest('.' + className);
}

using closest: http://api.jquery.com/closest/

Upvotes: 0

Related Questions