假设我有一个这样的HTML块。
<div class="text">
Hello <span class="word">world</span>! This is a test example.
</div>
我如何获取SPAN "word "元素后面的字符,在这种情况下就是(!)感叹号?
在vanilla JS中,你可以使用 Node.nextSibling
以获得下一个节点,然后 Node.textContent
和 Node.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
如果你在上面的例子中使用它。