Reputation: 35
I'm doing a simple class selection like this:
var myItem = $("#div-id h3.class-name");
this selection used to return just one item, but I added some code that may add more elements which has such class name. I would like to put in the variable the value of the only item (if there's one) or of the last (if it has many).
I've tried this but I get an error which says that length() is not a function.
var myItem = $("#div-id h3.class-name");
if (myItem.length() > 0){
myItem = myItem.last();
console.log("it has multiple items");
}
Can you help me understand how to achieve this?
Thank you!
Upvotes: 1
Views: 62
Reputation: 1749
I think it can help you.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#test:last").toggle();
});
});
</script>
</head>
<body>
<h2 id="test">This is a heading</h2>
<p id="test">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
Upvotes: 1