jQuery 在 div 中找到第一次出现的类

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

find first occurrence of class in div

jquery

提问by Amit

I have the below html structure, i want to find the inner html of first div with class as "popcontent" using jQuery

我有下面的html结构,我想使用jQuery找到第一个div的内部html,类为“popcontent”

<div>
<div class="popContent">1</div>
<div class="popContent">2</div>
</div>

回答by Codecraft

You will kick yourself..... :)

你会踢自己..... :)

$(".popContent:first").html()

回答by Hitesh Modha

first occurrenceof class in div

第一次出现在 div 中的类

$('.popContent').eq(0).html('value to set');

Second occurrenceof class in div

在 div 中第二次出现

$('.popContent').eq(1).html('value to set');

回答by Vivek

you can use :firstselector in this case

:first在这种情况下,您可以使用选择器

$('.popContent:first').text();

DEMO

演示

回答by rajasaur

$("div.popContent:first").html()

should give you the first div's content ("1" in this case)

应该给你第一个 div 的内容(在这种情况下为“1”)

回答by 2GDev

Use the Jquery :first selectorlike below :

使用Jquery :first 选择器,如下所示:

$(".popContent:first");

回答by Buksy

You could use document.querySelector()

你可以使用document.querySelector()

Returns the first element within the document (using depth-first pre-order traversal of the document's nodes|by first element in document markup and iterating through sequential nodes by order of amount of child nodes) that matches the specified group of selectors.

返回文档中与指定选择器组匹配的第一个元素(使用文档节点的深度优先预序遍历|按文档标记中的第一个元素,并按子节点数量的顺序遍历顺序节点)。

Since it is only looking for first occurence, it has better performance than jQuery

由于它只寻找第一次出现,因此它的性能比 jQuery 更好

var count = 1000;
var element = $("<span>").addClass("testCase").text("Test");
var container = $(".container");
var test = null;
for(var i = 0; i < count; i++) {
 container.append(element.clone(true));
}

console.time('get(0)');
test = $(".testCase").eq(0);
console.timeEnd('get(0)');
console.log(test.length);

console.time('.testCase:first');
test = $(".testCase:first");
console.timeEnd('.testCase:first');
console.log(test.length);

console.time('querySelector');
test = document.querySelector(".testCase");
console.timeEnd('querySelector');
console.log(test);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>

jsFiddle version of snippet

jsFiddle 版本的代码段

回答by renakre

$("div.popContent:first").html();

回答by rt2800

You can use the following jQuery expression

您可以使用以下 jQuery 表达式

alert(jQuery('div.popContent').eq(0).html());