Reputation: 53
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(){
});
Upvotes: 2
Views: 101
Reputation: 24965
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>
Upvotes: 0
Reputation: 665
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/
Upvotes: 0
Reputation: 207557
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>
Upvotes: 1
Reputation: 12152
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>
Upvotes: 1