{"name":"parent","type":"method","title":".parent()","deprecated":null,"removed":null,"desc":"Get the parent of each element in the current set of matched elements, optionally filtered by a selector.","categories":["traversing/tree-traversal","version/1.0"],"entries":[{"return":"jQuery","signatures":{"added":"1.0","argument":{"desc":"A string containing a selector expression to match elements against.","name":"selector","optional":"true","type":"Selector"}},"examples":[{"desc":"Shows the parent of each element as (parent > child). Check the View Source to see the raw html.","code":"\n$( \"*\", document.body ).each(function() {\n var parentTag = $( this ).parent().get( 0 ).tagName;\n $( this ).prepend( document.createTextNode( parentTag + \" > \" ) );\n});\n","css":"\n div, p {\n margin: 10px;\n }\n","html":"\n
p,\n span,\n em \n \n
\n\nHello
Hello Again
Given a jQuery object that represents a set of DOM elements, the .parent() method allows us to search through the parents of these elements in the DOM tree and construct a new jQuery object from the matching elements.
The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree. Also, $( \"html\" ).parent() method returns a set containing document whereas $( \"html\" ).parents() returns an empty set.
The method optionally accepts a selector expression of the same type that we can pass to the $() function. If the selector is supplied, the elements will be filtered by testing whether they match it.
Consider a page with a basic nested list on it:
\n\n<ul class=\"level-1\">\n <li class=\"item-i\">I</li>\n <li class=\"item-ii\">II\n <ul class=\"level-2\">\n <li class=\"item-a\">A</li>\n <li class=\"item-b\">B\n <ul class=\"level-3\">\n <li class=\"item-1\">1</li>\n <li class=\"item-2\">2</li>\n <li class=\"item-3\">3</li>\n </ul>\n </li>\n <li class=\"item-c\">C</li>\n </ul>\n </li>\n <li class=\"item-iii\">III</li>\n</ul>\n \n If we begin at item A, we can find its parents:
\n\n$( \"li.item-a\" ).parent().css( \"background-color\", \"red\" );\n \n The result of this call is a red background for the level-2 list. Since we do not supply a selector expression, the parent element is unequivocally included as part of the object. If we had supplied one, the element would be tested for a match before it was included.
\n "}]}