Hello I am trying to make changes to the below HTML code textContent however it includes a <i>
tag in it so how can I change the textContent? How do I edit the HTML tag in the script to keep the <i>
tag class but change only the text that is in it?
This is how the default HTML look like
This is what it looks like after I edited it
HTML Code
<a id="notificationUnread" class="dropdown-item">
<i class="fas fa-envelope mr-2"></i> 0 unread notifications
</a>
Script
var notificationUnread = document.getElementById('notificationUnread').textContent = "TEST"
You can target the last text node using lastChild
or childNodes[lastIndex]
and change its value using node.nodeValue="Something"
document.getElementById("notificationUnread").lastChild.nodeValue="Test"
or
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>
If you want to change the html inside your a tag, use this:
var notificationUnread = document.getElementById('notificationUnread').innerHTML = "your html here";
otherwise you can change the text only with replacing innerHTML to innerText
How about wrapping the text you want to change in a <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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.