Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find element within parent container with jQuery

Tags:

jquery

Im trying to target an element within my LI only im having trouble, I've read the jQuery documentation but cant figure out what im doing wrong?

On a click event I want to find an element and alter 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');
});
like image 542
Liam Avatar asked Apr 25 '12 23:04

Liam


People also ask

How do I find a specific parent in jQuery?

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.

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.

Which jQuery method returns the direct parent element of the selected element?

jQuery parent() Method The parent() method returns the direct parent element of the selected element.


1 Answers

Based on the following HTML (bear in mind I had to wrap the li with the ul, since an unwrapped li is 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're trying to find the h4 within the li. The problems you're having are multiple:

  1. Using parent() only looks up to the immediate parent element of the current element; use closest() instead, to look up through the ancestors until it finds a matching element,
  2. closest() (as mentioned) looks up through the ancestor elements, while you're trying to find an element among the descendants of the li element. Use find(),
  3. You were searching for an h4 element, which didn't exist. You needed (I assume) to find the h2 that was present in the DOM.

So:

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

JS Fiddle demo.

References:

  • closest().
  • find().
  • parent().
like image 151
David Thomas Avatar answered Oct 21 '22 07:10

David Thomas