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…
<li>
<h2>400</h2>
<form>
<input type='submit' class='click' value='send'>
</form>
</li>
$('.click').click(function(){
$(this).parent('li').closest('h4').html('asdasd');
});
Based on the following HTML (bear in mind I had to wrap the
liwith theul, since an unwrappedliis invalid HTML):And the following jQuery:
It seems you’re trying to find the
h4within theli. The problems you’re having are multiple:parent()only looks up to the immediate parent element of the current element; useclosest()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 thelielement. Usefind(),h4element, which didn’t exist. You needed (I assume) to find theh2that was present in the DOM.So:
JS Fiddle demo.
References:
closest().find().parent().