如何通过类名或ID来获得元素 [英] How to get element by classname or id
问题描述
我想通过angularjs找到HTML元素。
I am trying to find the element in html by angularjs.
下面是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"));
但它不工作,并试图 element.find
,但它仅适用于标签。
But it does not work, and tried element.find
but it only works for tag.
有没有办法,可以通过在angularjs ID或类名得到元素的功能?
Is there any function that can get element by id or classname in angularjs?
推荐答案
getElementsByClassName
是DOM文档的功能。这既不是一个jQuery也不是jqLite功能。
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");
敷在jqLite(或jQuery的,如果jQuery是前角加载):
Wrap it in jqLite (or jQuery if jQuery is loaded before Angular):
var wrappedResult = angular.element(result);
如果你想从一个指令的链接功能的元素
选择您需要访问DOM参考,而不是在jqLite参考 - 元素[0]
而不是元素
:
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');
}
另外,您可以使用 document.querySelector
功能(在这里需要期间如果选择类):
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);
演示: http://plnkr.co/edit/AOvO47ebEvrtpXeIzYOH?p=$p$pview
这篇关于如何通过类名或ID来获得元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!