Shashika Shashika - 2 months ago 7
jQuery Question

How to get sibling text of element in span using jquery?

I need to change a text in a span.

<span class="count_bottom">
<i class="blue">
<i class="fa fa-sort-asc"></i>
12%
</i>
From last seen
</span>


I only need to change
From last seen
text according to button click event.
How can I do this?

Answer

Filter out non-empty text nodes inside space and then replace with new content.

$('.count_bottom')
  // get all child nodes
  .contents()
  // filter out non-empty text node
  .filter(function() {
    // check node type and content
    return this.nodeType === 3 && this.nodeValue.trim().length;
    // replace it with new content  
  }).replaceWith('new text');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="count_bottom"><i class="blue"><i class="fa fa-sort-asc"></i>12% </i> From last seen</span>


With pure JavaScript

// get the `i` tag inside `span`
document.querySelector('.count_bottom > i')
  // get adjacent text node which is immediately after the element
  .nextSibling
  // update text content of the text node
  .textContent = 'new text';
<span class="count_bottom"><i class="blue"><i class="fa fa-sort-asc"></i>12% </i> From last seen</span>