How to get element by classname or id
getElementsByClassName
is a function on the DOM Document. It is neither a jQuery nor a jqLite function.
Don't add the period before the class name when using it:
var result = document.getElementsByClassName("multi-files");
Wrap it in jqLite (or jQuery if jQuery is loaded before Angular):
var wrappedResult = angular.element(result);
If you want to select from the element
in a directive's link function you need to access the DOM reference instead of the the jqLite reference - element[0]
instead of element
:
link: function (scope, element, attrs) {
var elementResult = element[0].getElementsByClassName('multi-files');
}
Alternatively you can use the document.querySelector
function (need the period here if selecting by class):
var queryResult = element[0].querySelector('.multi-files');
var wrappedQueryResult = angular.element(queryResult);
Demo: http://plnkr.co/edit/AOvO47ebEvrtpXeIzYOH?p=preview
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.""
@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