.addClass not working on jqLite / Angular.js

17k views Asked by At

I've been struggling lately to understand why the .addClass function was not working on jqLite

element.addClass('active')    

Element returns me an array of html elements, tested that over and over to be sure. I can hide(), show() , add a .css or get one, or even set .attr , but addClass resists me.

edit: element is a path in a svg block , and this is the reason that seems to make the addClass function irrelevant, still trying to fix it.

element is a jqLite object

Thank you.

3

There are 3 answers

0
Reyraa On

JqLite methods don't work with elements selected by plain javascript DOM selectors like querySelector or document.getElementById(). if you need so, first select it with javascript selectors then wrap it in angular.element:

var element = document.querySelector('a[target="_blank"]');
var angElement = angular.element(element);

or simply

var myElement = angular.element( document.querySelector('a[target="_blank"]') );

then you could use JqLite methods:
first example:

angElement.addClass('active');

second one:

myElement.addClass('active');
0
dinodsaurus On

I think this is generally a bad idea... Adding classes in angular is usually not done jquery style, you should use ng-class directive https://docs.angularjs.org/api/ng/directive/ngClass

the directive is quite simple to use..

<div ng-class="{active: show}"></div>

This div will get class active when $scope.show is true

1
Srinivas Paila On

You have to use a directive to add and remove classes

HTML:

    <div ng-controller="MyCtrl">
        <input type="button" active value='One' />
        <input type="button" active value='Two' />
        <input type="button" active value='Three' />
    </div>

JS:

    var app = angular.module('myApp',[]);

    app.directive('active', function() {
        return {
            link: function(scope, element, attrs) {
                element.bind('click', function() {
                    //Remove the active from all the child elements
                    element.parent().children().removeClass('active');

                    //Add active class to the clicked buttong
                    element.addClass('active');
                })
            },
        }
    });

    function MyCtrl($scope) {
    }

Here is the link to the fiddle.