1

Normally this would not be a problem, but this time I don't control the dom. Anyway

<dt>foo</dt>
<dd>bar</dd>
<dd>bar
    <div id="myElem">baz</div>
</dd>
<dd>bar</dd>
<dd>bar</dd>
<dd class="moo">bar</dd> <-- I want to get this one
<dd>bar</dd>
<dd>bar</dd>
<dd class="moo">bar</dd>
<dd>bar</dd>
<dd>bar</dd>

Here is what I have tried

$('#myElem').closest('dd').next('.moo').something();
$('#myElem').closest('dd').nextUntil('.moo').something();

However non of these get the next sibling with the class.

Anyone know how to traverse this?

Fresheyeball
  • 29,567
  • 20
  • 102
  • 164

2 Answers2

3

Try

$('#myElem').closest('dd').nextAll('.moo:first').something();

or

$('#myElem').closest('dd').nextUntil('.moo').next().something();

I don't know zepto but from a quick check of the docs it doesn't look like you can do it with a simple chain. Try

var $dd = $('#myElem').closest('dd');
var $moo = $dd.next();
while (!$moo.is('.moo')){
    $moo = $moo.next();
    if ($moo.length == 0) break;
}

DEMO

Musa
  • 96,336
  • 17
  • 118
  • 137
2

You can accomplish by creating a simple new method:

/**
* Get the next element of a particular class, relative to a different element.
*/ 
var nextOfClass = function(relativeTo, className) {
    var el = relativeTo, nextEl;

    // Leading period will confuse Zepto. 
    if (className[0] === '.') className = className.slice(1); 

    while (el.next()) {

        // If target element is found, stop
        if (el.hasClass(className)) return el; 

        nextEl = el.next(); 
        if (nextEl.length === 0) {
            // No more siblings. Go up in DOM and restart loop to check parent
            el = el.parent(); 
            continue; 
        }

        el = nextEl;  

         // End of doc. Give up. 
        if (el.parent().length === 0) return false;
    }
};

Then you can simply use the following method:

var moo = nextOfClass($("#myElem"), '.moo'); 
hawkharris
  • 2,570
  • 6
  • 25
  • 36
  • 1
    -1 Extending the native `Object.prototype` for something library specific is a really bad practice. What happens when someone does `{}.nextOfClass('.moo');`? Better to extend zepto properly. http://zeptojs.com/#$.fn – Fresheyeball Dec 11 '13 at 21:09
  • +1, much better. But why not use `$.fn`? It would allow for `$('#myElem').nextOfClass('.moo')` without extending `Object`. – Fresheyeball Dec 12 '13 at 16:50