.addClass not working on jqLite / Angular.js

Nkogo picture Nkogo · Nov 10, 2014 · Viewed 16.7k times · Source

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.

Answer

Reyraa picture Reyraa · Nov 22, 2014

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');