I am currently trying to find the parent of a parent of an element. I have a link being clicked that is in a <td>, and I'd like to get the <tr> object.
Why wont "$(this).parent().parent()" work? What will?
Thanks,
Brendan
Edit: It appears an error in my syntax was throwing the whole thing off. "$(this).parent().parent()" does in fact work, but I wound up going with $(this).closest('tr')" because it seems like the most efficient solution.
The best way would probably be using closest:
$(this).closest('tr');
Check out the documentation:
Closest works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned.
It should work. You can also try $(this).parents(tag) , where tag is the tag you want to find.
For example:
$(this).parents("tr:first")
Will find the closest tr "up the chain".
That should work... you might try
$(this).parents(':eq(1)');
The .parents(selector) says get all ancestors that match the selector
and the :eq(1) says find the oneth (zero-indexed, so the second) element in the list
This snippet has performed for me in the past:
$(this).parent().parent();
Post some code for us to see if there might be another problem somewhere...
also try
$(this).closest('div.classname').hide();
If you have any sort of id/class for the parent, you can use parents() but that will give you all parents up to the < body > unless you filter() or stop it some other way like
$(this).parents('.myClass');
Hope this helps someone :)
Try wrapping the $(this).parent() into an jQuery object like $($(this).parent()) I often find the need to do this to make sure I have a valid jquery object. From there you should be able to get a hold of the parents parent, or using the prev() perhaps.
var getParentNode = function(elem, level) {
level = level || 1;
for (var i = 0; i < level; i++) {
if (elem != null) {
elem = elem.parentNode;
}
}
return elem;
}
.closest() is not always best option specially when you have same element construct.
<div>
<div>
<div>
</div>
</div>
</div>
You can do parent of a parent and it's very easy:
var parent = $('.myDiv').parent();
var parentParent = $(parent).parent();
var parentParentParent = $(parentParent).parent();
etc.
Related
I am currently trying to find the parent of a parent of an element. I have a link being clicked that is in a <td>, and I'd like to get the <tr> object.
Why wont "$(this).parent().parent()" work? What will?
Thanks,
Brendan
Edit: It appears an error in my syntax was throwing the whole thing off. "$(this).parent().parent()" does in fact work, but I wound up going with $(this).closest('tr')" because it seems like the most efficient solution.
The best way would probably be using closest:
$(this).closest('tr');
Check out the documentation:
Closest works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned.
It should work. You can also try $(this).parents(tag) , where tag is the tag you want to find.
For example:
$(this).parents("tr:first")
Will find the closest tr "up the chain".
That should work... you might try
$(this).parents(':eq(1)');
The .parents(selector) says get all ancestors that match the selector
and the :eq(1) says find the oneth (zero-indexed, so the second) element in the list
This snippet has performed for me in the past:
$(this).parent().parent();
Post some code for us to see if there might be another problem somewhere...
also try
$(this).closest('div.classname').hide();
If you have any sort of id/class for the parent, you can use parents() but that will give you all parents up to the < body > unless you filter() or stop it some other way like
$(this).parents('.myClass');
Hope this helps someone :)
Try wrapping the $(this).parent() into an jQuery object like $($(this).parent()) I often find the need to do this to make sure I have a valid jquery object. From there you should be able to get a hold of the parents parent, or using the prev() perhaps.
var getParentNode = function(elem, level) {
level = level || 1;
for (var i = 0; i < level; i++) {
if (elem != null) {
elem = elem.parentNode;
}
}
return elem;
}
.closest() is not always best option specially when you have same element construct.
<div>
<div>
<div>
</div>
</div>
</div>
You can do parent of a parent and it's very easy:
var parent = $('.myDiv').parent();
var parentParent = $(parent).parent();
var parentParentParent = $(parentParent).parent();
etc.
Say I have HTML that looks like this:
<div>
<div>
<div class="calendar start">
</div>
</div>
<div>
<div class="calendar end">
</div>
</div>
</div>
We can assume that the start and end will always be on the same "level" of a branch from each other, and will at some point share a common parent.
Without knowledge of the exact HTML structure, how would I find calendar end from calendar start? What if they are nested further down?
Edit: For clarification. I want to start at start's parent. Search all child elements for end. Then move to the next parent, and search all child elements...etc till I find end. I am wondering if this is possible with built in JQuery functions, without writing my own DOM traversal logic.
You can do it like below, But it is a costlier process.
var parentWhichHasCalEnd =
$($(".calendar.start").parents()
.get().find(itm => $(itm).find(".calendar.end").length));
var calEnd = $(".calendar.end", parentWhichHasCalEnd);
DEMO
Explanation: We are selecting the .start element first, then we are retrieving its parent elements. After that we are converting that jquery object collection to an array of elements by using .get(). So that we could use .find(), an array function over it. Now inside of the callBack of find we are checking for .end over each parent element of .start, if a parent has .end then we would return that parent. Thats all.
You could get more understanding, if you read .get(), .find(), and arrow functions.
You can use jQuery#next() method from .start parent element
var startSelector = $('body > div > div:nth-child(3) > .start')
var endSelector = secondStart.parent().next().find('.end');
I think this method is faster rather than jQuery#children() method, but you can benchmark it if you want to
btw you may check my answer based on this JSBin
i don't know if i got this right but have you tried children function in jquery
$( ".calender" ).children( ".end" )
and for the parent you can use parent() function so you can first check the parent then the children or vicversa
edit:
if you dont know the exact structure the better way is to find the common parent and then search it's children :
$( ".calender.start").closest('.common-parent').children('.calender.end');
closest function give the nearest parent
Try:
$('.start').parent().parent().find('.end');
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/
I am trying to compare if the two td elements are the same within 1 table.
I have
var element = $('.table td');
$('table:odd td','.table').each(function(){
if(element.is(this)){
console.log('find')
}
)}
I want to check if the element is the same as this but my codes don't seem to work here.
Can anyone give me a hint for it? Thanks a lot
regular DOM nodes can be compared against each other, and using get(0) will get you the first DOM node from the jQuery collection :
var element = $('.table td');
$('table:odd td','.table').each(function(){
if (element.get(0) === this ){
console.log('find');
}
});
It does look like element would contain more than one element, especially as you're iterating the same selector with an added :odd on the next line, so the comparison seems a little strange, and will probably return false ?
<div id="dad">
<img id="mum">
<input>
</div>
With jQuery, how could i get access to the input element, get is value or set it for example? I can't work out how to access something on the same level.. and i dont want to be using ID's, just parent/child nodes so i can use the code for loads of dad div's
Thanks!
an addition to Zed,
$(this).parent().children('input');
if you give a name to your input field then you can easily select throughout the others,
$(this).parent().children('input[name=my_input]');
then you can give any value as:
$(this).parent().children('input[name=my_input]').val('any value');
Sinan.
var myEl = $("#dad").children(":input");
$(this).parent().children() ?
Try this, to find the first child input element:
jQuery("div").find("input:first")
If i understand question, you would like achieve input from mum leve?
So try $("#mum ~ input")...
BTW, great site to search jquery function by category http://visualjquery.com/ +nice example.
I guess you want to find siblings (node with same depth and same parent and in DOM tree)
$(el).next() - next element (sibling) for all elements in the set
$(el).nextAll - all following siblings
$(el).nextUntil - all following siblings, stop on some condition (not including first "bad match").
Besides, you have next adjacent selector (+) and next sibling selector.
The same about prev, prevAll and prevUntil.
And you even have a siblings method.
Check this out.