Reputation:
I don't understand why when i looking for how to get an element in list of element selected by class name like in traditional JS, I've always seen complicated answers .
document.getElementsByClassName('anyclass')[1]
so, i have found out myself that i cant do that (may be its the wrong approach)
$('.anyclass')[1]
but i get a DOM element! so logically i tried
$('.anyclass')[1][0]
and it doesnt work 'TypeError: $(...)[0][0] is undefined' Anyone can explain why ? thank you!
Upvotes: 1
Views: 1284
Reputation: 1413
The :first
pseudo-class is equivalent to :eq( 0 )
. It could also be written as :lt( 1 )
. While this matches only a single element, :first-child can match more than one: One for each parent.
here
$('.anyclass:first)
Quick example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$($(".t")[1]).css("background-color", "yellow");
});
</script>
</head>
<body>
<p class=t>This 1.</p>
<p class=t>This 2.</p>
<p class=t>This 3.</p>
</body>
</html>
'
$('.anyclass')[0].attr("src"); you can use like this .
after your comment:
$(".anyclass")[1]
is a DOM element not a jquery object. Simply wrap it as jquery $($("td")[1]).width()
Upvotes: 0
Reputation: 133403
I think you need .eq(index)
var secondElement = $('.anyClass').eq(1); //jQuery object
var domElement = secondElement[0]; //DOM element
console.log(secondElement, domElement)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='anyClass'>1</div>
<div class='anyClass'>2</div>
Upvotes: 1
Reputation: 117
var elm = document.createElement("div");
var jelm = $(elm); //convert to jQuery Element
var htmlElm = jelm[0]; //convert to HTML Element
Upvotes: 1