How to get element by classname or id

后端 未结 4 482
栀梦
栀梦 2020-11-27 12:35

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

Here is the html:

相关标签:
4条回答
  • 2020-11-27 13:15

    @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

    0 讨论(0)
  • 2020-11-27 13:16

    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.""

    0 讨论(0)
  • 2020-11-27 13:23

    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. :)

    0 讨论(0)
  • 2020-11-27 13:24

    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

    0 讨论(0)
提交回复
热议问题