Find element within parent container with jQuery

前端 未结 1 1901
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 14:56

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

相关标签:
1条回答
  • 2020-12-17 15:14

    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().
    0 讨论(0)
提交回复
热议问题