I am trying to retrieve the parent of an <a> element's parent (grandparent?). I want to find that grandparent, then find a <b> tag in that element, then store that text as a variable to publish elsewhere on the page. I've been trying to use the parent() function but without success.
Here's the code I tried:
$('.mixPlayCell a').click( function() { var title = $(this).parent().get(0).parent().get(0).text(); alert(title); });
The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.
The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.
To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object. The parentNode property is read-only, which means you can not modify it.
jQuery parentsUntil() Method The parentsUntil() method returns all ancestor elements between the selector and stop. An ancestor is a parent, grandparent, great-grandparent, and so on.
.parent() By using the jQuery .parent() method, you can traverse one level up the DOM tree and return the direct parent of a specified element. It is also possible to add a selector expression ($()).
In this tutorial, learn how to get second child element of list in jQuery. The short answer is: use the jQuery nth-child () selector to select the second child item. You can also use the jQuery eq () method to select the second item of the list element. Let’s find out with the examples given below.
Given a jQuery object that represents a set of DOM elements, the parent() method traverses to the immediate parent of each of these elements in the DOM tree and constructs a new jQuery object from the matching elements. This method is similar to .parents(), except .parent() only travels a single level up the DOM tree.
This parents () method in jQuery traverse all the levels up the selected element and return that all elements. Here selector is the selected element whose all parent need to find. Parameters: It does not accept any parameter.
For selecting a second parent
parents(':eq(1)')
looks smoother than
parent().parent()
Also, you might find that
closest('ul')
fits the job better.
try:
$(this).parent().parent().find('.thingtofind').text();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With