Jquery: using closest selector issue
Question
I am trying to learn some jQuery and working through some tutorials. I am very early in the process and learning to move through the DOM with .parent()
, .parents()
and .closest()
.
I was chugging a long and then became perplexed as to why I couldnt select a certain element (p
tag with a class) and add a class to it.
Mind you.. these are just exercises.. I wouldnt select something this way but I want to see that it can be done.
<div class="container">
<h1>Hello World</h1>
<h2>This is a tutorial</h2>
<p class="para">This is a tutorial for jquery and jquery UI</p>
<div class="container">
<ul class="listItem container">
<li>Hello 1</li>
<li>Hello 2</li>
<li>
<ul class="nest">
<li>Nest 1</li>
<li>Nest 2</li>
</ul>
</li>
</ul></div>
</div>
jQuery
//$('ul.listItem').find('li').first().addClass('listItem2');
//$('li').parent().removeClass('listItem');
$('ul.nest').children('li:first').addClass('listItem');
$('ul.listItem').closest('.container').removeClass('container');
$('ul.listItem').children('li:nth-child(2)').addClass('listItem3');
$('ul.listItem').closest('.para').addClass('listItem2');
//console.log($('ul').parents('.container'));
console.log($('ul').closest('.container'));
console.log($('ul.listItem').closest('.para'));
My question is why will it not select the p
tag in this example and add the class listItem2
to it? It finds the container tag just fine but not the p
tag, or even the para
class. In the console log it shows nothing, but yet finds the container class just fine. Just thought I should know before moving on. Thanks
Solution
.closest()
searches all the parents of an element (and even the element itself) for a match.
$('ul.listItem').closest('.para')
This doesn't work because .para
isn't a parent of the ul
. The ul
's parent's are the two .container
divs (and I guess the <body>
and <html>
tags).
To select the <p>
, you can do:
$('ul.listItem').parent('div.container').prev('.para')