Jquery select previous element with class - javascript

I have 3 elements:
<div class='first'>First</div>
<div class='second'>Second</div>
<div class='target'>Target</div>
on click on target div I test .prev() function in my js
$(document).on('click','.target',function(){
console.log($(this).prev().html());
console.log($(this).prev('.first').html());
});
Output is like: 'Second undefined', but should be like: 'second first' if I understand right the parameter of .prev() usage.
How can I get first previous element with certain class then?
Here is fiddle for you: http://jsfiddle.net/0fzgzce5/

From jQuery docs,
.prev()
Description: Get the immediately preceding sibling of each element in
the set of matched elements, optionally filtered by a selector.
To select all preceding sibling elements, rather than just the
preceding adjacent sibling, use the .prevAll() method.
http://api.jquery.com/prevAll/
So you should use console.log($(this).prevAll('.first').html());

You can make use of sibling() which will return the element with specific class and at same level as calling elment. But make sure that there is no same div after target
$(document).on('click','.target',function(){
console.log($(this).siblings('.second').html());
console.log($(this).siblings('.first').html());
});
DEMO
OR you can use prevAll()
$(document).on('click','.target',function(){
console.log($(this).prevAll('.second').html());
console.log($(this).prevAll('.first').html());
});
DEMO

Use prevAll() instead of prev()
$(document).on('click', '.target', function() {
alert($(this).prevAll('.second').html());
alert($(this).prevAll('.first').html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='first'>First</div>
<div class='second'>Second</div>
<div class='target'>Target</div>

You can use also $("div:eq(3)") to get the exact element. Best example is $("ul li:eq(3)")

In your second console.log(), yous this is still .target and it does not have .first class so it is saying undefined.
To get the first dive, do:
console.log($(this).prev().prev().html());

Jquery .prev() always get immediate preceding sibling.
if you pass a selector as parameter it will filter the preceding element to match with, if it did not match it will return undefined, in your case this is happening
$('.target').prev().html()
is same as
$('.target').prev('.second').html();
which will return "Second"
If you pass any selector other than '.second' it alway return undefined so, your case
$('.target').prev('.first').html();
is as exprected, returning undefined because '.first' is not matching with preceding element selector.
Update:
if you want to get First the use
$('.target').prev().prev().html();

Related

Getting ALL First links in a specific class

So I know that using "a:first" will get the first link of a page. Lets assume we have the following:
<div class="masterclass">
Link 1
Link 2
</div>
<div class="masterclass">
Link 1
Link 2
</div>
Naturally I can use the following code to get the first "a" of the class "masterclass"
$('.masterclass a:first').click(function() {
alert('yayfirstlink');
});
However I do not understand how to get the first link of every "masterclass"
You need to use find() here because your selector will find all the anchor elements with in .masterclass then filter only the very first one. But when you use .find(), it will find all the .masterclass elements first then will find the first anchor element in each of them.
$('.masterclass').find('a:first').click(function() {
alert('yayfirstlink');
});
or if you are sure that the target element will be the first child of its parent then you can use :first-child
$('.masterclass a:first-child').click(function() {
alert('yayfirstlink');
});
Try this,
var oFirstAnchor = $(".masterclass a:first-child");
$(".masterclass a:first-child") is what you are looking for.
so:
$('.masterclass a:first-child').click(function() {
alert('yayfirstlink');
});
This is how u loop through each of the masterclass and get the first link of it.
i don't know what you want to do with it though so i can only provide this
$(document).ready(function(){
var fields = $('.masterclass a:first-child');
$.each(fields, function(index, val){
alert(index);
});
});
this alerts the current links array index
http://jsfiddle.net/kBd82/6/
I would recommend using the first of type selector for this.
$('.masterclass a:first-of-type')
This way it will always select the first anchor tag in each masterclass div even if you put other things in the div later.
http://api.jquery.com/first-of-type-selector/

jQuery .index() strangeness

I'm by no means a jQuery (or JavaScript) expert so forgive me if I'm misunderstanding or overlooking something. I have the following HTML:
<html>
<body>
<div class="ted">Ted</div>
<div class="ted">Ted</div>
<div class="tim">Tim</div>
<div class="ted">Ted</div>
<div class="tim">Tim</div>
</body>
</html>
And the following JS:
$('.ted').click(function() {
alert($(this).index());
});
When I click a div with the class '.ted' the alert should show the index of that div.
Clicking the first div alerts '0' (expected), the second div alerts '1' (expected). However, clicking the last '.ted' div (the fourth in the list) alerts '3' - why is this not giving an index of 2? (as JS arrays are 0 based) and this is the third '.ted' div?
It's as if $('.ted') is actually bringing back all the divs in the list?
Example here: http://jsfiddle.net/nha2f/6/
The .index() method docs make this behaviour clear. Here's the relevant part (emphasis added):
If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
Since the third element that matches your selector is actually the fourth child of its parent, it has an index of 3.
Continue reading through the documentation to find the solution to your problem:
If a selector string is passed as an argument, .index() returns an integer indicating the position of the original element relative to the elements matched by the selector.
So, you can pass the same selector to .index() and it will return the index of the element relative to the matched set:
alert($(this).index(".ted"));
.index() returns the index of the clicked element in it's parent, relative to it's siblings. Not compared to other divs with the same event listeners / class / id. Your third '.ted' div is the fourth child of your body.
To get the behavior you want, add a selector to your index call: Fiddle
$('.ted').click(function() {
alert($(this).index(".ted"));
});
When you pass a selector into index, it tells jQuery to look for the element in that set. If you don't, it looks to see where it is relative to all of its sibling elements.
Or alternately, remember the list of ted elements and then invert things: Fiddle
var teds = $(".ted");
teds.click(function() {
alert(teds.index(this));
});
When you pass an element into index, that tells jQuery to look for that element in the set.
the index is the child within the parent. If you want to enumerate the .ted elements try this:
$('.ted').each( function( i, a ){
$(a).click( function(){
alert( i ); // <- should be 0, 1 or 2.
} );
} );

Is there a method in jQuery that will traverse up the dom tree from an element and check selectors before its parent element

For example:
<div class="mainWrapper">
<div class="FirstLayer">
<input class="foo" value="foo" />
</div>
<div class="SecondLayer">
<div class="thirdLayer">
<input class="fee" />
</div>
</div>
</div>
Lets say I have the input.fee as a jQuery object and I also need to get the value of input.foo.
Now I know I can use a multitude of approaches such as $(this).parents(':eq(2)').find('.foo') but I want to use this one method on layouts which will have varying levels and numbers of nodes.
So I am wondering if there is a method which will simply start from .fee and just keep going up until it finds the first matching element, .prevAll() does not appear to do this. There are many .foo and .fee elements and I need specifically the first one above the .fee in context.
How about this:
$('input.fee').closest(':has("input.foo")')
.find('input.foo').val();
Here's JS Fiddle to play with. )
UPDATE: Kudos to #VisioN - of course, parents:first is well replaced by closest.
This will select the previous input.foo
// self might have siblings that are input.foo so include in selection
$( $("input.fee").parentsUntil(":has(input.foo)").andSelf()
// if input.off is sibling of input.fee then nothing will
// be returned from parentsUntil. This is the only time input.fee
// will be selected by last(). Reverse makes sure self is at index 0
.get().reverse() )
// last => closest element
.last()
//fetch siblings that contain or are input.foo elements
.prevAll(":has(input.foo), input.foo")
// first is closest
.first()
// return jQuery object with all descendants
.find("*")
// include Self in case it is an input.foo element
.andSelf()
.filter("input.foo")
// return value of first matching element
.val()
jQuery.closest() takes selector and does exactly what you need - finds the first matching element that is parent of something. There's also jQuery.parents() that does take a selector to filter element ancestors. Use those combined with find method and you're set.
$('input.fee').closest('.mainWrapper").find('.foo') does the trick, doesn't it?

How to get the container id in javascript or in jquery

I have some HTML blocks look like
<li id="item261">
<div class="itemdesc">
<a class="icon-hide">Hide</a>
</div>
</li>
And i have a jquery like
$(document).ready(function()
{
$('.icon-hide').click(function(){
var elemId = $(this).parent().attr("id");
});
});
I need the ID of the "li" tag on click of ".icon-hide". how can i achive this? any help..
I'd suggest:
$('.icon-hide').click(function(){
var elemId = $(this).closest('li').attr('id');
});
This is because parent() as implied in the name of the method looks at the parent of the element returned by the selector (the parent is the div); whereas closest() continues up the ancestor tree to match the first selector passed to the method.
You could, instead, use parents(), however the important difference between closest() and parents() is that closest() returns zero or one match, whereas parents() will continue all the way to the root element and return every match it finds, so it can return zero, one or many matches.
Another difference is that parents() starts searching from the current element's parent, whereas closest() starts with the current element itself, so it's quite easily possible, using closest() for the method to return the current/$(this) element itself.
References:
closest().
parent().
parents().
$(this).closest('li[id]').attr('id')

Can anyone explain this bizarre behavior in jQuery next?

It works:
<div class="xpav">
Create
</div>
<div class="apr" style="display: none;">
sometext
</div>
<script>
$('.xpav').click(function() {
$(this).next(".apr").slideDown("fast");
})
</script>
It doesn't:
<div class="xpav">
Create
</div>
<br />
<div class="apr" style="display: none;">
sometext
</div>
<script>
$('.xpav').click(function() {
$(this).next(".apr").slideDown("fast");
})
</script>
Why breaks it?
.next() only looks at the element that comes after the given element, then checks that element against the selector if it's provided. In your second example, since the br is there and doesn't have the apr class, it isn't picked up. From the API docs:
Description: Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
Your second example requires the use of .nextAll() instead to search through all the next siblings:
$('.xpav').click(function() {
$(this).nextAll(".apr").slideDown("fast");
});
To pick up only the first .apr that's matched, use .eq(0):
$('.xpav').click(function() {
$(this).nextAll(".apr").eq(0).slideDown("fast");
});
under my impression next() only works if the sibling objuect is the same DOM tage,
what does work is:
$('.xpav').click(function() {
console.log($(this).next(".apr"));
$(this).siblings(".apr").slideDown("fast");
})
It's exactly that what the documentations says: "Description: Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector."
http://api.jquery.com/next/
Because next() takes you to the immediate next DOM element which is <br />. Why not use this:
$(".apr").slideDown("fast");
Simply because you are using the next() method in your code. The next DOM element from $('.xpav') in the second version of your code is a <br />, and since that doesn't match the filter, it doesn't slide anything down!
If you want it to work, you should consider using nextAll() instead of next(), as the latter ONLY gets the very next DOM element, where the former gets all siblings that are after itself in the DOM.

Categories