如何使用jquery在span中获取元素的兄弟文本?

时间:2016-09-12 10:08:05

标签: javascript jquery html text siblings

我需要更改跨度中的文本。

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

我只需要根据按钮点击事件更改From last seen文字。 我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

过滤掉空间内的非空文本节点,然后替换为新内容。

&#13;
&#13;
$('.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');
&#13;
<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>
&#13;
&#13;
&#13;

使用纯JavaScript

&#13;
&#13;
// 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';
&#13;
<span class="count_bottom"><i class="blue"><i class="fa fa-sort-asc"></i>12% </i> From last seen</span>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以在i中选择第一个span元素,然后使用nextSibling属性获取其下一个兄弟文本。

&#13;
&#13;
$("button").click(function(){
    $(".count_bottom > i")[0].nextSibling.nodeValue = "New value";
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Change text</button>
<span class="count_bottom">
    <i class="blue">
        <i class="fa fa-sort-asc"></i>
        12% 
    </i> 
    From last seen
</span>
&#13;
&#13;
&#13;