Closest Previous Sibling

Get the closest sibling to the target <textarea> without using id's or classes or attributes on the textarea and spans elements.

by r3wt

HTML

<div>
    <span extra-data="1">1</span>
    <br />
    <textarea target="1"></textarea>
    
    <span extra-data="2">2</span>
    <textarea target="2"></textarea>
    
    <span extra-data="3">3</span>
    <textarea target="3"></textarea>
</div>

<p></p>
*notice the `Break` tag between the first Span and Textarea
<h3>Problem:</h3>
<p>How to get the closest (in this case) previous sibling by element type</p>
<strong>a better solution, using custom data tag and target</strong>

CSS

p {
    margin: 2em;
}

JavaScript

$('div').on('keyup', 'textarea', function() {
    var target = $("span[extra-data='"+$(this).attr('target')+"']");
    target.text($(this).val());
});