Reputation: 1655
I´m trying to get the text with a click-event of some nested spans in an order closest to widest below my specific span 'annotation-container'. With my current code I get only the text of the clicked span. I need the text of every span below the span 'annotation-container'. After every text, I have to fire a function. Thank you for your hints.
Example 1 - click on 'test' (lowest level of nested span):
1st iteration text: This is a test (highest level of nested spans)
2nd text: a test (next lower level...)
3rd text: test (clicked span)
$('body').on('click', 'span.annotation', function(e) {
var text = $(e.target).closest('span').text();;
console.log(text);
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="annotation-container">
<span class="annotation">
<span class="annotation">This is
<span class="annotation">a
<span class="annotation">test</span>
</span>
</span>
</span>
<span class="annotation">
<span class="annotation">One more
<span class="annotation">great</span>
<span class="annotation">test
<span class="annotation">!</span>
</span>
</span>
</span>
</span>
Upvotes: 0
Views: 230
Reputation: 12452
Use e.stopPropagation()
instead of e.preventDefault()
to stop event bubbeling. And possible this
instead of e.target
.
And notice that you closed the span
after great
in your initial example:
<span class="annotation">great</span>
And why do you set your selector to body
if you have a .annotation-container
? It would be mutch nicer to use this.
$('.annotation-container .annotation').on('click', function(e) {
$($(this).parentsUntil('.annotation-container > .annotation').get().reverse()).each(function() {
console.log($(this).text());
});
console.log($(this).text());
e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="annotation-container">
<span class="annotation">
<span class="annotation">This is
<span class="annotation">a
<span class="annotation">test</span>
</span>
</span>
</span>
<span class="annotation">
<span class="annotation">One more
<span class="annotation">great
<span class="annotation">test
<span class="annotation">!</span>
</span>
</span>
</span>
</span>
</span>
Upvotes: 2