Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Missing prevUntil - $('#demo').prev('a'); #185

Closed
alvarotrigo opened this issue Apr 12, 2018 · 4 comments
Closed

Missing prevUntil - $('#demo').prev('a'); #185

alvarotrigo opened this issue Apr 12, 2018 · 4 comments

Comments

@alvarotrigo
Copy link

alvarotrigo commented Apr 12, 2018

Having:

<a href="#">Text</a>
<b>Text 2</b>
<a id="demo" href="#">Text 3</a>

We want to return the prev a, not the <b> element:

$('#demo').prev('a'); // <a href="#">Text</a>

In jQuery they call it internally prevUntil:

nextUntil: function(elem, i, until) {
    return dir(elem, "nextSibling", until);
},
prevUntil: function(elem, i, until) {
   return dir(elem, "previousSibling", until);
},
@alvarotrigo alvarotrigo changed the title Missing prevUntil - prev('a'); Missing prevUntil - $('#demo').prev('a'); Apr 12, 2018
@alvarotrigo
Copy link
Author

I would suggest something on these lines:

function prevUntil(item, selector){
	var prev = item.previousElementSibling
	while(prev && !prev.matches(selector)){
    	    prev = prev.previousElementSibling;
        }
    
    return prev;
}

@alvarotrigo
Copy link
Author

Perhaps something like:

function until(item, selector, fn){
        var sibling = item[fn]
        while(sibling && !sibling.matches(selector)){
            sibling = sibling[fn];
        }
        
        return sibling;
    }

    function prevUntil(item, selector){
        return until(item, selector, 'previousElementSibling')
    }

    function nextUntil(item, selector){
        return until(item, selector, 'nextElementSibling')
    }

@CarloMartini
Copy link
Contributor

@alvarotrigo Since you are already proposing code solutions, I think you can directly open some pull requests.

@camsong
Copy link
Owner

camsong commented Apr 1, 2019

@alvarotrigo looks good to me, can you raise a PR?

@camsong camsong closed this as completed Apr 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants