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');
});
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.
$() = 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.
jQuery parent() Method The parent() method returns the direct parent element of the selected element.
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:
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()
,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()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With