What is the method for adding a CSS class to the textContent in a HTML element?

Hi there, I'm currently trying to make some changes to the textContent of the HTML code below. However, it contains an <i> tag, so I'm wondering how I can change the textContent without affecting the <i> tag itself. Is there a way to edit the HTML tag in the script while preserving the <i> tag's class but only modifying the text within it?

This is what the original HTML looks like:

https://i.sstatic.net/J69Ti.png

And here is what it looks like after my edits:

https://i.sstatic.net/c8SoZ.png

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"

Answer №1

To target the final text node, utilize lastChild or childNodes[lastIndex] and modify its content with 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>

Answer №2

In order to modify the content within your anchor tag in HTML, simply follow this method:

var notificationUnread = document.getElementById('notificationUnread').innerHTML = "Insert your customized HTML here";

Alternatively, if you wish to only change the text without altering the HTML structure, replace innerHTML with innerText.

Answer №3

One way to update specific text is by enclosing it 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"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for rendering XML tags in a web browser without relying on the <xmp> or <pre> elements

I've been facing a challenge with displaying an Ajax returned xml file in String format on IE9. When rendered as a String, IE fails to recognize the XML tags and treats them as invalid HTML tags, resulting in only the text being displayed and creatin ...

AngularFire: Retrieve the $value

Having an issue logging the service.title to the console as it keeps returning as a strange object. .factory('service', function($firebase, FBURL, $routeParams) { var ref = new Firebase(FBURL + "services/" + $routeParams.serviceId); var titl ...

Leveraging the outcome of a for loop in order to set a condition within an else if statement

How can I condition my third else if statement based on the result of a for loop? //If player clicks centre on first move go in corner square if (current[4] === playerToken && this.state.stepNumber === 1) { let move = c ...

Discovering the initial element with a data attribute above zero using JQuery

I am working with a set of divs that have the class .item-wrap. At the moment, I am able to select the first div using this code snippet: $(".item-wrap:first").trigger( "click" ); Each .item-wrap element comes with a data-amount attribute. My challenge ...

Custom Typescript type that runs concurrently with the base type is disregarded

Assumption: When creating a custom type that mirrors an existing type, the expectation is for variables assigned to that type to maintain it and not default back to the base type. In the function f provided below, the expected return type should be Dog ins ...

What's the best way to showcase data in a column dynamically depending on its specific columns?

I have an array of objects representing columns and another array representing table data. I need to dynamically display the data in the specified columns. Some objects have 3 key-values which should be displayed in specific columns. The second object in ...

Loop through each HTML element and store it in a JavaScript array

I currently have a webpage with 3 select buttons named "Season". I am trying to figure out which buttons are selected and receive their values as an array on my webpage. Below is the code I am using: var season_array = $.each($(form).children("input.sele ...

The variable ReactFauxDOM has not been declared

Exploring the combination of D3 and React components. Utilizing OliverCaldwell's Faux-DOM element has led me to encounter a frustrating error message stating "ReactFauxDOM is not defined”. Despite following the npm install process correctly... It s ...

Is it possible to nest ng-repeat and access $first and $last properties simultaneously

Below is the form that I am currently working with, <tbody ng-repeat="attGroup in attributesGroups"> <tr> <td class="vcenter text-right"> &nbsp;&nbsp;<a href="javascript:" ng-click="!$last && up ...

Transferring user input from UI Dialog using AJAX requests

Check out this code snippet: HTML <div id="resume-begin" style="background:#CCCCCC; display:inline-block;"> <img src="/images/plus-plus.png" style="display:inline;" class="trigger"/> </div> <div class="input-resume-data" style="d ...

A duo of adjacent buttons styled with HTML, CSS, and Bootstrap

I'm encountering an issue with the layout of my design. On my product page, I have two buttons placed on top of each other because one is within a form (refer to the image). https://i.sstatic.net/cS9TI.jpg I would like to position the two buttons s ...

How do I navigate back to show the initial parent component instead of the nested child component in ReactJS?

The data flow in my React app goes like this: SubmitForm -parent-> Results -parent-> Presentation -parent-> ButtonBackToSearch I am delving into ReactJS and trying to adopt the right mindset for creating single-page applications. Currently, I am ...

Can you guide me on how to establish a cookie within a selenium webdriver javascript script?

I am trying to figure out how to set a cookie using a basic webdriver script: WDS.sampleResult.sampleStart(); //WDS.driver.manage().addCookie(new Cookie("connect.sid", "s%3AeexeZcd_-S23Uh30e3Dmd4X9PskWF08s6m5hDurDa5Jj66SupmmiqvKEjAg6HGigl0o0V%2B9R7m4", ...

How to nullify the valueChanges pipe in Angular RxJS until the observable is resolved

A challenge I am facing is piping the valueChanges from a select element to trigger the appropriate API request and displaying a spinner until the response is received. Additionally, I am trying to utilize publish() and refCount() methods so that I can use ...

Getting started with TypeScript in combination with Node.js, Express, and MongoDB

I'm a beginner in working with TypeScript, Node.js, Express, and MongoDB. I need guidance on the end-to-end flow for these technologies. Can someone please suggest steps or provide links for a step-by-step process? What is the procedure to compile/r ...

Tips for setting up Reaction Roles in discord.js?

Having some trouble implementing this functionality, especially with my reaction role. Wondering if I am using the correct functions/methods. Any help would be greatly appreciated. New to discord bot development and might have a simple question, but any a ...

When using the `Document.write()` method, an error is returned stating, "Uncaught TypeError: Cannot read property 'document' of null"

I am currently integrating Angular2 into a website as the front-end framework, and it will be displayed on another website using an iframe. When working with the HTTP post method, I am able to receive a JSON response. Here is the API Post method that retu ...

Problem with automatic saving of workspaces in DBeaver

Currently using DBeaver with Oracle server and encountering a recurring error related to workspace save. I have searched online for a solution, but all results seem to focus on meta data explanations. As someone new to DBeaver, I would greatly appreciate ...

Troubleshooting a Basic jQuery Validation Problem

I've been attempting to incorporate the "Refactoring rules" segment from http://jqueryvalidation.org/reference/ However, I'm struggling to figure out the appropriate placement for the $.validator code. Currently, I'm inserting it like this: ...

How come I'm unable to send the HTTP request contents as a response using express.js?

I'm currently in the process of setting up a basic web server using node.js and express.js. Essentially, I want the server to return the content of the request as a response. Below is the code I have implemented: const express = require('express& ...