Find item in parent container using jQuery

I am trying to target an element inside my LI just because of problems, I read the jQuery documentation, but can't figure out what I'm doing wrong?

In the click event, I want to find the element and change the html inside ...

http://jsfiddle.net/68ePW/3/

<li> <h2>400</h2> <form> <input type='submit' class='click' value='send'> </form> </li> $('.click').click(function(){ $(this).parent('li').closest('h4').html('asdasd'); }); 
+8
jquery
source share
1 answer

Based on the following HTML (remember that I had to wrap li with ul since the expanded li invalid HTML):

 <ul> <li> <h2>400</h2> <form> <input type='submit' class='click' value='send'> </form> </li> </ul>​​​​​​​​​​​​​​​​​​ 

And the following jQuery:

 $('.click').click(function(){ $(this).parent('li').closest('h4').html('asdasd'); }); 

It seems you are trying to find h4 in li . The problems that you have are several:

  • Using parent() only searches for the immediate parent of the current element; use closest() instead to browse through the ancestors until it finds the matching element,
  • closest() (as mentioned) looks at the elements of the ancestor while you are trying to find the element among the descendants of the li element. Use find() ,
  • You were looking for the h4 element that was not there. You needed (I suppose) to find the h2 that was present in the DOM.

So:

 $('.click').click(function(){ $(this).closest('li').find('h2').html('asdasd'); }); 

JS Fiddle demo .

Literature:

+19
source share

All Articles