![](/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.