How to select an element by classname using jqLite?

AngularjsAngularjs DirectiveJqlite

Angularjs Problem Overview


I'm trying to remove jquery from my Angular.js app in order to make it lighter, and put Angular's jqLite instead. But the app makes heavy use of find('#id') and find ('.classname'), which are not supported by jqLite, only 'tag names' (as per documentation)

wondered what do u feel would be the best approach to change it. One approach I thought about is to create custom HTML tags. for example: change
<span class="btn btn-large" id="add-to-bag">Add to bag</span>

to

<a2b style="display:none;"><span class="btn btn-large" >Add to bag</span></a2b>

and

$element.find('#add-to-bag') 

to

$element.find('a2b')

Any thoughts? other ideas?

thanks

Lior

Angularjs Solutions


Solution 1 - Angularjs

Essentially, and as-noted by @kevin-b:

// find('#id')
angular.element(document.querySelector('#id'))

//find('.classname'), assumes you already have the starting elem to search from
angular.element(elem.querySelector('.classname'))

Note: If you're looking to do this from your controllers you may want to have a look at the "Using Controllers Correctly" section in the [developers guide][1] and refactor your presentation logic into appropriate directives (such as <a2b ...>).

[1]: http://docs.angularjs.org/guide/controller "developers guide"

Solution 2 - Angularjs

angualr uses the lighter version of jquery called as jqlite which means it doesnt have all the features of jQuery. here is a reference in angularjs docs about what you can use from jquery. Angular Element docs

In your case you need to find a div with ID or class name. for class name you can use

var elems =$element.find('div') //returns all the div's in the $elements
    angular.forEach(elems,function(v,k)){
    if(angular.element(v).hasClass('class-name')){
     console.log(angular.element(v));
}}

or you can use much simpler way by query selector

angular.element(document.querySelector('#id'))

angular.element(elem.querySelector('.classname'))

it is not as flexible as jQuery but what

Solution 3 - Angularjs

If elem.find() is not working for you, check that you are including JQuery script before angular script....

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLiorView Question on Stackoverflow
Solution 1 - Angularjspsema4View Answer on Stackoverflow
Solution 2 - Angularjshannad rehmanView Answer on Stackoverflow
Solution 3 - AngularjsancajicView Answer on Stackoverflow