Jquery Get Text of Nested Selector not child

How To Access keyword-text e.g java On click keyword-remove class.

First Of all it's outside keyword-remove scope can not use $(this). I want to access nested selector span text.

<span class="keyword">
  <span class="keyword-remove"></span>
  <span class="keyword-text">java</span>
</span>

$(document).on("click",".keyword-remove", function(){

});
728x90

4 Answers Jquery Get Text of Nested Selector not child

As the click event is on the span, it cannot be empty. If it is empty you cannot click it. After entering some data in the span select the sibling span using the siblings function and print the textContent. Alternatively .next can be used instead of siblings

$(document).on("click",".keyword-remove", function(){
   console.log($(this).siblings('span')[0].textContent)
   });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="keyword"><span class="keyword-remove">First span </span><span class="keyword-text">java</span></span>

1 months ago

use next() to select the next sibling of the element you clicked.

$(document).on("click",".keyword-remove", function(){
  console.log($(this).next('.keyword-text').text())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="keyword">
  <span class="keyword-remove">REMOVE</span>
  <span class="keyword-text">java</span>
</span>

1 months ago

You can use the following code block -

$(document).on("click",".keyword-remove", function(){
  console.log($(this).next().find('.keyword-text').text())
});

Working Example - https://jsfiddle.net/0wmnxdrp/1/

1 months ago

Personally I would use closest() paired with a following find(). The reason being, this removes the positional logic from the equation, and you only rely on the parent child relationship.

$(document).on("click",".keyword-remove", function(){
  console.log($(this).closest('.keyword').find('.keyword-text').text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="keyword">
  <span class="keyword-remove">X</span>
  <span class="keyword-text">java</span>
</span>

1 months ago