Find element within parent container with jQuery

jquery

Solution

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:

- 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,

- `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()`,

- 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()`.

Problem

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'); }); ```

Original source