[angularjs] How to get element by classname or id

I am trying to find the element in html by angularjs.

Here is the html:

<button class="btn btn-primary multi-files" type="button">
   <span>Choose multiple files</span>
</button>
<br/><br/>
<input ng-file-select type="file" multiple  style="display: none"/><br/>

I am trying to get the button element by class name multi-files, then I tried

var multibutton = angular.element(element.getElementsByClassName(".multi-files"));

But it does not work, and tried element.find but it only works for tag.

Is there any function that can get element by id or classname in angularjs?

This question is related to angularjs

The answer is


You don't have to add a . in getElementsByClassName, i.e.

var multibutton = angular.element(element.getElementsByClassName("multi-files"));

However, when using angular.element, you do have to use jquery style selectors:

angular.element('.multi-files');

should do the trick.

Also, from this documentation "If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite.""


If you want to find the button only by its class name and using jQLite only, you can do like below:

var myListButton = $document.find('button').filter(function() {
    return angular.element(this).hasClass('multi-files');
});

Hope this helps. :)


@tasseKATT's Answer is great, but if you don't want to make a directive, why not use $document?

.controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  var dumb = function (id) {
  var queryResult = $document[0].getElementById(id)
  var wrappedID = angular.element(queryResult);
  return wrappedID;
};

PLUNKR