The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.
The JavaScript getElementsByClassName is used to get all the elements that belong to a particular class. When the JavaScript get element by class name method is called on the document object, it searches the complete document, including the root nodes, and returns an array containing all the elements.
Step 1) Add HTML:Add a class name to the div element with id="myDIV" (in this example we use a button to add the class).
Use the element. classList. contains() method to check if an element contains a specific class name.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With