Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement "prevUntil" in Vanilla JavaScript without libraries?

I need to implement the functionality of jQuery's prevUntil() method in Vanilla JavaScript.

I've got several <div> elements on the same level:

<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

I'm trying to use an onclick event to find the event.target's previousSiblings until a certain criteria is reached (for example, a class name match) then stop.

How do I achieve this?

like image 587
Francisc Avatar asked Sep 08 '11 20:09

Francisc


People also ask

What vanilla Javascript means?

Vanilla JavaScript refers to using plain Javascript without any additional libraries or frameworks. The term became popular when Eric Wastl created the Vanilla JS site in 2012 as a joke. The site tries to bring attention to the fact that you can use just plain Javascript in many cases.

What is vanilla jQuery?

Vanilla JS helped the developers in creating dynamic websites. Then came jQuery, a library of tools created by developers around the world, using Javascript. In simple words, jQuery is a lightweight and easy to use JavaScript library that helps in creating complex functionalities with few lines of coding.

Which built in method in jQuery?

on() is a built-in method in jQuery. It is used to assign one (or more than one) event handler to selected elements.


1 Answers

This answer was previously published here in response to a similar question .

There are a few ways to do it.

Either one of the following should do the trick.

// METHOD A (ARRAY.FILTER, STRING.INDEXOF)
var siblings = function(node, children) {
    siblingList = children.filter(function(val) {
        return [node].indexOf(val) != -1;
    });
    return siblingList;
}

// METHOD B (FOR LOOP, IF STATEMENT, ARRAY.PUSH)
var siblings = function(node, children) {
    var siblingList = [];
    for (var n = children.length - 1; n >= 0; n--) {
        if (children[n] != node) {
            siblingList.push(children[n]);
        }  
    }
    return siblingList;
}

// METHOD C (STRING.INDEXOF, ARRAY.SPLICE)
var siblings = function(node, children) {
   siblingList = children;
   index = siblingList.indexOf(node);
   if(index != -1) {
       siblingList.splice(index, 1);
   }
   return siblingList;
}

FYI: The jQuery code-base is a great resource for observing Grade A Javascript.

Here is an excellent tool that reveals the jQuery code-base in a very streamlined way. http://james.padolsey.com/jquery/

like image 65
abbotto Avatar answered Oct 27 '22 01:10

abbotto