Javascript jQuery 中“getElementsByTagName”的等价物是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4398553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the equivalent of 'getElementsByTagName' in jQuery?
提问by Shaoz
What's the equivalent of getElementsByTagName()
in jQuery? I just want to create a collection of elements in jQuery so I can iterate through them and do something with each item.
getElementsByTagName()
jQuery 中的等价物是什么?我只想在 jQuery 中创建一个元素集合,这样我就可以遍历它们并对每个项目做一些事情。
Many thanks!
非常感谢!
回答by karim79
$("tagnamehere")
So:
所以:
$("div").each(function() {
// do something exciting with each div
$(this).css("border", "1px solid red");
// do something by directly manipulating the wrapped DOM element
this.style.border = "1px solid red";
// do something only if this particular div has a class of 'pretty'
if($(this).hasClass("pretty")) {
$(this).text("I am the pretty one");
}
});
or just:
要不就:
// apply some css to all div elements
$("div").css("border", "1px solid red");
Keep in mind that when you use jQuery to select a number of elements, e.g. $("span")
, any method you invoke on the object will happen on all matched elements. Think of it as 'implicit iteration' - e.g. $("span").hide();
will hide all span elements on the page.
请记住,当您使用 jQuery 选择多个元素时,例如$("span")
,您对对象调用的任何方法都将发生在所有匹配的元素上。将其视为“隐式迭代” - 例如$("span").hide();
将隐藏页面上的所有跨度元素。
See:
看:
回答by James Wiseman
Just use the element selector
只需使用元素选择器
$('elementname')
E.g.
例如
$('div')
And to do the iteration:
并进行迭代:
$('div').each(function(){
var $this = $(this);
//insert code here
});
You may not have to iterate, however, as a method called upon the collection will be called for each item in the collection, so
但是,您可能不必迭代,因为将为集合中的每个项目调用调用该集合的方法,因此
$('div').hide();
...will hide all divs.
...将隐藏所有 div。
回答by boumbh
Given a string tagName
, this statement:
给定一个字符串tagName
,这个语句:
document.getElementsByTagName(tagName)
...could be written using jQuery:
...可以使用jQuery编写:
$(tagName)
Given a native DOM element element
and a string tagName
, this statement:
给定一个原生 DOM 元素element
和一个 string tagName
,这个语句:
element.getElementsByTagName(tagName)
...could be written using jQuery:
...可以使用jQuery编写:
$(element).find(tagName)
Note :Using getElementsByTagName
you get native DOM elements, meanwhile using jQuery statements you get jQuery objects. If you want native DOM elements with jQuery you could use get()
- How do I pull a native DOM element from a jQuery object?
注意:使用getElementsByTagName
您获得原生 DOM 元素,同时使用 jQuery 语句您获得 jQuery 对象。如果您想要带有 jQuery 的本机 DOM 元素,您可以使用get()
-如何从 jQuery 对象中提取本机 DOM 元素?
回答by Geovas
Just need put something like:
只需要放一些类似的东西:
var some = $('[name="tagname"]');