首页 > 解决方案 > Find closest span element with given class within next sibling

问题描述

I have a textarea element as follows:

<textarea class="additional contactNameInput" id="additional1" name="additional1" placeholder="Additional requests..."></textarea>

Then straight after I have HTML as follows:

<div>
  <p>Intro</p>
  <p>Additional text: <span class="addedText"></span></p>
<div>

I want the span to be completed with the text added in the textarea. However, because I have a lot of these repeated, I need to use siblings / parents / children to target these. I wrote the following:

$(".additional1").keyup(function() {
  $(this).siblings('div:first').nextAll('.addedText').html($("#additional1").val());
});

But this doesn't work. When I remove the .nextAll('addedText') then it does work, but obviously replaces the whole div. How do I target this span element with class addedText.

Furthermore, I would then need to replace the #additional1' so that for each element with this document the contents of the particular textarea being used is selected.

I've been playing around for hours with different combinations and I cannot seem to get the selectors right.

标签: jqueryselectorchildren

解决方案


Some small tweaks only needed:

$(".additional").keyup(function() {
  $(this).next('div').find('.addedText').html($(this).val());
});

for

<textarea class="additional contactNameInput" id="additional1" ....
  • change the selector to the class .additional
  • use .next("div") to get the next div
  • use .find(".addedText") to find child items of that div
  • use $(this).val() to get the text from the active textarea

推荐阅读