Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Closest Previous Sibling [duplicate]

Tags:

html

jquery

I'm aware by going over the jQuery traversal documentation that there isn't a jQuery function that will do what I'm looking for so I'm asking what combination (if there is one) will do the trick.

If we have 1 <span> for every <textarea> on a page, and without having to get creative by adding id's or classes or data-attributes etc. would like to get the closest previous <span> to the <textarea> that is the target of the current keydown event.

What combination of jQuery traversal functions can we use to solve this problem? I've researched and tried everything I know to.

Check out this Fiddle to better visualize this problem.

like image 772
id.ot Avatar asked Dec 12 '25 10:12

id.ot


1 Answers

there isn't a jQuery function that will do what I'm looking for

Actually, all you want is prev.

Use prev('span') to get the previous element matching the given selector.

$('div').on('keydown', 'textarea', function () {

        $(this).prev('span').text($(this).val())

})

See http://jsfiddle.net/aQ83s/2/

Note that, in the keydown event, the value of the textarea hasn't changed yet.

like image 94
meagar Avatar answered Dec 13 '25 22:12

meagar