find first occurrence of class in div

Jquery

Jquery Problem Overview


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

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

Jquery Solutions


Solution 1 - Jquery

You will kick yourself..... :)

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

Solution 2 - Jquery

first occurrence of class in div

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

Second occurrence of class in div

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

Solution 3 - Jquery

you can use :first selector in this case

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

DEMO

Solution 4 - Jquery

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

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

Solution 5 - Jquery

You could use 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

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

Solution 6 - Jquery

Use the Jquery :first selector like below :

$(".popContent:first");

Solution 7 - Jquery

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

Solution 8 - Jquery

You can use the following jQuery expression

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmitView Question on Stackoverflow
Solution 1 - JqueryCodecraftView Answer on Stackoverflow
Solution 2 - JqueryHitesh ModhaView Answer on Stackoverflow
Solution 3 - JqueryVivekView Answer on Stackoverflow
Solution 4 - JqueryrajasaurView Answer on Stackoverflow
Solution 5 - JqueryBuksyView Answer on Stackoverflow
Solution 6 - Jquery2GDevView Answer on Stackoverflow
Solution 7 - JqueryrenakreView Answer on Stackoverflow
Solution 8 - Jqueryrt2800View Answer on Stackoverflow