![](/img/trans.png)
[英]how do i check the textcontent inside a button. the if statement isnt recognising the text
[英]How do I append a textContent with a CSS class inside?
您好,我正在嘗試更改下面的 HTML 代碼 textContent 但是它包含一個<i>
標簽,那么我該如何更改 textContent? 如何在腳本中編輯 HTML 標記以保留<i>
標記 class 但僅更改其中的文本?
這是默認 HTML 的樣子
這是我編輯后的樣子
HTML 代碼
<a id="notificationUnread" class="dropdown-item">
<i class="fas fa-envelope mr-2"></i> 0 unread notifications
</a>
腳本
var notificationUnread = document.getElementById('notificationUnread').textContent = "TEST"
您可以使用lastChild
或childNodes[lastIndex]
定位最后一個文本節點,並使用node.nodeValue="Something"
更改其值
document.getElementById("notificationUnread").lastChild.nodeValue="Test"
或者
let nodes=document.getElementById('notificationUnread').childNodes
nodes[nodes.length-1].nodeValue= "TES"
//let nodes=document.getElementById('notificationUnread').childNodes //nodes[nodes.length-1].nodeValue= "TES" //Without span document.getElementById("notificationUnread").lastChild.nodeValue="Test Without span" //With span document.querySelector("#notificationUnread2 >.text-notification").innerText="Test with span"
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> <!--without span --> <a id="notificationUnread" class="dropdown-item"> <i class="fas fa-bell mr-2"></i> 0 unread notifications </a> <br> <!--with span --> <a id="notificationUnread2" class="dropdown-item"> <i class="fas fa-bell mr-2"></i> <span class="text-notification">0 unread notifications</span> </a>
如果要更改 a 標簽內的 html,請使用以下命令:
var notificationUnread = document.getElementById('notificationUnread').innerHTML = "your html here";
否則您只能通過將 innerHTML 替換為 innerText 來更改文本
如何將要更改的文本包裝在<span>
中
<a id="notificationUnread" class="dropdown-item">
<i class="fas fa-envelope mr-2"></i> <span class="link-text">0 unread notifications<span>
</a>
document.querySelector('#notificationUnread .link-text').innerText = "TEST"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.