gsklee
gsklee

Reputation: 4944

AngularJS - Simulate .prev() using jqLite only?

In angular.element there is only a next() method but prev(). Is there any way to simulate the behavior of prev() with Angular/jqLite only?

Upvotes: 5

Views: 2061

Answers (2)

Andriy Horen
Andriy Horen

Reputation: 2950

You can also use native DOM api to get previous/next sibling:

var prevNode = element[0].previousElementSibling;
var prev = angular.element(prevNode); // optional

var nextNode = element[0].nextElementSibling;
var next = angular.element(nextNode); // optional

Upvotes: 6

Davide Icardi
Davide Icardi

Reputation: 12219

I'm not an angularjs expert but I think that you can write a code like (not tested...):

function prevOf(yourElement) {
  var parent = yourElement.parent();
  var children = parent.children();

  var prev;
  for (var i = 1; i < children.length; i++){
    if (children[i] === yourElement[0]) {
      prev = children[i-1];
    }
  }

  return prev;
}

Upvotes: 3

Related Questions