Search code examples
javascriptangularjsangularjs-directivejqlite

Angularjs: how to find an element based on a data-attribute value?


I've got the following directive:

template: '<div data-div="outer"><div data-div="inner"></div></div>',
link: function postLink(scope, elem, attrs) {
       var outer = elem.find('[data-div="outer"]');
       var inner = elem.find('[data-div="inner"]');
       outer.css({
           'background': 'red',
           'width': "100%",
           'height': "100%",
       });
       inner.css({
           'background': 'blue',
           'width': "50%",
           'height': "100%",
       });
    }

Based on this post, i tried these selectors. but im using jQLite, not JQuery.

so, how to find an element based on a data-attribute value?

http://plnkr.co/edit/FeJWvwnKjOZwAIABigtA?p=preview


Solution

  • You can use querySelector() (or querySelectorAll() for multiples) to get a similar find() behavior when using jqLite...

    function postLink(scope, elem, attrs) {
        var outer = angular.element(elem[0].querySelector('[data-div="outer"]'));
        var inner = angular.element(elem[0].querySelector('[data-div="inner"]'));
        outer.css({
           'background': 'red',
           'width': "100%",
           'height': "100%",
        });
        inner.css({
           'background': 'blue',
           'width': "50%",
           'height': "100%",
        });
    }