Javascript 带有类的 div 的 jquery 选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10557620/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:51:34  来源:igfitidea点击:

jquery selector for div with class

javascriptjquery

提问by Patrick Jeon

I tried this below. I think the return Object of $("div.tab_select")[0]isn't a jQuery Object, but I can't even use pure javascript method.

我在下面试过这个。我认为$("div.tab_select")[0]的返回对象不是 jQuery 对象,但我什至不能使用纯 javascript 方法。

Is there any way to make it jQuery Object? for instance $($("div.tab_select")[0])..I know this's silly;

有没有办法让它成为jQuery对象?例如$($("div.tab_select")[0])..我知道这很愚蠢;

Thank you for reading.

感谢您的阅读。

var tmp = $("div.tab_select")[0]; 
alert(tmp); //This gives me HTMLDivElement collectly. But I can't use any of javascript..

alert(tmp.nodeName); //But this give me error "Uncaught TypeError: Cannot read property 'nodeName' of undefined"

tmp.hide(); //Neither, I can't use this.

回答by jmar777

// all divs with tab_select class
$('div.tab_select')

// first div with tab_select class
$('div.tab_select:first')

// or CSS pseudo selector which is slightly faster than the first jQuery 
// shortcut 
$('div.tab_select:first-of-type')

// or
$('div.tab_select').first()

// or
$('div.tab_select:eq(0)')

// or
$('div.tab_select').eq(0)

回答by Sagiv Ofek

if you want a jQuery object use var tmp = $("div.tab_select:first")instead.

如果你想要一个 jQuery 对象,请var tmp = $("div.tab_select:first")改用。

var tmp = $("div.tab_select")[0]will return the DOM element (if exists)

var tmp = $("div.tab_select")[0]将返回 DOM 元素(如果存在)

回答by dav1d

Just do $(tmp). [0] gives you the HTML-Element not the JQuery instance.

就做$(tmp)。[0] 为您提供 HTML-Element 而不是 JQuery 实例。

回答by kishanio

I read it somewhere that css selectors are faster.

我在某处读到 css 选择器更快。

$('div.tab_select:nth-child(n)').<method>

here is the e.g.

这是例如