Finding a specific element tag in angularJS

7.6k views Asked by At

I'm working with angularJS and would like to remove/modify the class of a specific child element (who's class/id is unknown because it is being added to the parent element dynamically).

I understand that using angular you can say something like:

    angular.element('someknownParentClass').addClass('newClass');

However, I want to do something similar to:

    angular.element('.someknownParentClass').find('i').addClass('newClass');

The class 'someknownParentClass' is a class assigned to an 'a' tag, and inside this tag, I have an 'i' tag with a glyphicon icon class that I would like to change from inside a specific function. It seems like this method isn't working. I know angular's jqLite has a children() attribute, but i'm a little unsure of how to use this or if it would be useful in this case, or maybe using jQuery with angular would be my best option (from what I understand, that's different than jqLite). Any suggestions?

2

There are 2 answers

0
Ghan On

I'm assuming you're doing this in a directive, in which case you can do something like:

var elem = angular.element('.someknownParentClass');
var iElems = elem.children('i');
iElems.addClass("newClass");

If you're more comfortable in jQuery, I don't see a problem in using it in an angular directive instead. According to the docs, angular.element is an alias for jQuery: https://docs.angularjs.org/api/ng/function/angular.element

$('.someknownParentClass').find('i').addClass("newClass");
0
Patrick On

You shouldn't need to use angular.element if you are doing things within a directive. If you want to use angular.element in code, you are probably better off using jQuery. I put together a sample jsfiddle that binds a directive to a pre-defined class (some-known-parent-class) and searches for all the "i" elements under it and adds newClass class to it:

var mod = angular.module("myApp", []);
mod.directive("someKnownParentClass", function () {
    return {
        restrict: "C",
        link: function (scope, element, attrs) {
            element.find("i").addClass("newClass");
        }
    }
});

This way, you are decoupling the direct DOM manipulation (i.e. angular.element) through using a directive to do the manipulation. Fiddle here.