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

14,625

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%",
    });
}
Share:
14,625
rnrneverdies
Author by

rnrneverdies

Nothing in the world is a gift. Whatever there is to learn has to be learned the hard way. Turn this concepts into a viable way of life by a process of repetition. Everything new in our lives, such as the concepts we are learning, must be repeated to us to the point of exhaustion before we open ourselves to it. Said that, Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than right now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!

Updated on June 13, 2022

Comments

  • rnrneverdies
    rnrneverdies almost 2 years

    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