如何在Javascript或JQuery中获取元素后的字符?

问题描述 投票:-1回答:1

假设我有一个这样的HTML块。

<div class="text">
    Hello <span class="word">world</span>! This is a test example.
</div>

我如何获取SPAN "word "元素后面的字符,在这种情况下就是(!)感叹号?

javascript jquery dom
1个回答
3
投票

在vanilla JS中,你可以使用 Node.nextSibling 以获得下一个节点,然后 Node.textContentNode.nodeValue 来获取其值。

const word = document.querySelector('.word');

console.log(word.nextSibling.nodeValue);
<div class="text">
  Hello <span class="word">world</span>! This is a test example.
</div>

你可以很容易地将其改编成jQuery。

const $word = $('.word');

// Simply get the native JS object and access `.nextSibling.nodeValue` on that:
console.log($word.get(0).nextSibling.nodeValue);
<div class="text">
  Hello <span class="word">world</span>! This is a test example.
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

请注意这两者之间的区别 Node.nextSibling,返回节点,以及 NonDocumentTypeChildNode.nextElementSibling所以它将返回 null 如果你在上面的例子中使用它。

© www.soinside.com 2019 - 2024. All rights reserved.