63

I am working in a directive and I am having problems using the parameter element to find its childs by class name.

.directive("ngScrollList", function(){
    return {
        restrict: 'AE',
        link: function($scope, element, attrs, controller) {

            var scrollable = element.find('div.list-scrollable');

            ...
        }
      };
})

I can find it by the tag name but it fails to find it by class name as I can see in the console:

element.find('div')
[<div class=​"list-viewport">​…​</div>​,<div class=​"list-scrollable">​…​</div>​]
element.find('div.list-scrollable')
[]

Which would be the right way of doing such thing? I know I can add jQuery, but I was wondering if wouldn't that be an overkill....

vtortola
  • 34,709
  • 29
  • 161
  • 263
  • Not sure if this [helps](http://stackoverflow.com/questions/17283697/angularjs-how-to-find-using-jqlite)? – Pete Jul 07 '14 at 21:35

2 Answers2

107

jQlite (angular's "jQuery" port) doesn't support lookup by classes.

One solution would be to include jQuery in your app.

Another is using QuerySelector or QuerySelectorAll:

link: function(scope, element, attrs) {
   console.log(element[0].querySelector('.list-scrollable'))
}

We use the first item in the element array, which is the HTML element. element.eq(0) would yield the same.

FIDDLE

Mosho
  • 7,099
  • 3
  • 34
  • 51
31

In your link function, do this:

// link function
function (scope, element, attrs) {
  var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}

Also, in your link function, don't name your scope variable using a $. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.

tomexx
  • 2,301
  • 2
  • 20
  • 33
pje
  • 2,458
  • 1
  • 25
  • 26