The Styles of Class Are Being Disregarded by Elements Added Through the DOM

I have a div called "editorPathDisplay" where I want to display a path like root/something/anotherthing, with the '/' characters in bold to distinguish the separation. My approach is to populate the editorPathDisplay div with spans: the first would contain "root" with no classes, the next would contain "/" with the class "bold", and so on.

The issue arises when the span only contains a slash '/'; it does not appear bold. I have tried using different class names and styles, but nothing seems to work for procedurally-added spans with the sole content of a slash '/'. Below is my JavaScript code and the resulting page structure - which appears correct! Please help me identify what I am doing wrong!

CODE:

var pathDisplay = document.getElementById("editorPathDisplay");
pathDisplay.textContent = "PATH: ";
var path = selectedObj.dataset.path;

var pathList = path.split("/");

for (var i = 0; i < pathList.length; i++) {
    var unformattedSpanInsert = document.createElement("span");
    unformattedSpanInsert.textContent = pathList[i];
    pathDisplay.appendChild(unformattedSpanInsert);

    if (i < pathList.length - 1) {
        var spanInsert = document.createElement("span");
        spanInsert.classList.add("bold");
        spanInsert.textContent = "/"; 
        pathDisplay.appendChild(spanInsert);
    }
}

RESULT 1:

https://example.com/result1.png

RESULT 2:

spanInsert.textContent = "/";

https://example.com/result2.png

Could you please help me understand why this is happening and suggest a solution? If you have a better way to achieve my goal of bolding the slashes in the displayed path string, I would appreciate your input. All I need is to display the path variable string with bolded slashes.

Thank you.

Answer №1

When you only need to emphasize a specific character or group of characters, another approach is utilizing CSS fonts without separating the path into individual elements. You can use the unicode-range property to select the bolded character from a different font file designated as bolder. Here's an example:

@font-face {
  font-family: 'editorPathDisplayFont';
  font-style: normal;
  src: url(https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxIIzI.woff2) format('woff2');
}
@font-face {
  font-family: 'editorPathDisplayFont';
  font-style: normal;
  src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmYUtfBBc4.woff2) format('woff2');
  unicode-range: U+002F;
}

#editorPathDisplay {
  font-family: editorPathDisplayFont;
}
<div id="editorPathDisplay">  
  dataOutput/testObj/innerObj
</div>

Answer №2

Consider modifying your font selection, as it appears that the current font lacks a bold style for the forward slash character.

If you are looking for an alternative approach to achieve the same outcome, you can utilize CSS styling.

@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100;900&display=swap');


li {
  list-style: none;
  display: inline-block;
  font-family: 'Roboto', sans-serif;
  font-weight: 100;
}

li:not(:last-child)::after {
  content: ' / ';
  font-weight: 900;
}
<ul>

  <li>Home</li>
  
  <li>Account</li>
  
  <li>Billing</li>

</ul>

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

Calling Ajax inside each iteration loop

I have encountered numerous posts discussing this topic, but the solutions I came across do not quite suit my needs. Some experts suggest changing the code structure, however, I am unsure of how to go about doing that. What I desire: 1) Retrieve a list ...

Newbies struggle with styling HTML elements within nested IDs

I am new to learning HTML and struggling with working with IDs and classes within IDs and classes. Based on my understanding, an ID is denoted by a # symbol. So if I wanted to style an ID within another ID, would it be written like: #ID1 #ID2 { ... ...

Dynamic visual content (map)

I'm currently working on creating an interactive image for my website where clicking on points A, B, C, ... N will reveal bubbles with images and text inside them. Would anyone be able to provide guidance on how to achieve this? Or direct me to resou ...

Elements are failing to respond to the padding and margin adjustments in my CSS styling

I've been experimenting with creating a visually appealing div that serves as the centerpiece of a website. Imagine it resembling a standard "news" link. The width set at 80%, an image aligned to the left with a border, a headline detailing the lates ...

To include a slash or not before the assets path in HTML - that is the question

Should the use of / in front of paths in HTML pages be considered a good practice? If using / for paths, is it necessary to configure a <base url=""> in the page? An issue arises with a generated CSS file that includes the following: background-ima ...

CORS response header is not included

Is it the company's responsibility () to rectify one of their endpoints or is it an issue with my code? I have tested all other endpoints () using the same code below and they all function correctly, except for the specific one in question. The erro ...

Vue: Utilizing an ESlint guideline for eliminating the usage of "this" in templates

I'm currently on the lookout for an ESlint rule that can detect and remove instances of this being used before props or data. For instance: <template> <div v-if="this.foo"></div> </template> In an ideal scenario, ...

Steps for building a 2x2 grid of tables in HTML

I am struggling to design a 2x2 grid of collapsible tables in HTML. I have been experimenting with different solutions, but I haven't found one that works seamlessly. When I collapse the top left table, it messes up the alignment of the bottom row tab ...

Having trouble retrieving information from ajax to php

I'm struggling to understand why this code is not functioning as expected: idcurso= res[0]; idusuario= res[1]; semana= res[2]; fecha=res[3]; asistencia= true; $.ajax({ type: "POST", url: '/test/7/tomarasistencia.php', data: { ...

Encountered an error with ng build --prod while attempting to import a JavaScript file within the app module

Is it possible to import a javascript file into my app module without access to the ts file? import { OtherComponent } from './node_modules/blahblah/OtherComponent.js' While trying to declare this component in @NgModule and running "ng build -- ...

What is a more efficient method for verifying the value of an object within an array that is nested within another object in JavaScript?

Is there a more efficient way to check for an object in an array based on a property, without having to go through multiple checks and avoiding potential errors with the ? operator? /** * An API returns a job object like: * { id: 123, name: 'The Job ...

What's the best way to perfectly align table text in the center both horizontally and vertically?

Despite encountering similar or potentially identical questions, I have attempted the suggested solutions without success. My aim is to design a table that centers text both vertically and horizontally, ideally using flex. However, the structure of the ta ...

A tutorial on how to switch classes between two tabs with a click event in Vue.js

I am having an issue with my spans. I want to implement a feature where clicking on one tab changes its color to red while the other remains gray. I have tried using class binding in my logic but it's not working. How can I solve this problem and make ...

Summing numbers inputted into text boxes generated by a looping mechanism

Currently, I have a function that uses a for loop to generate multiple text boxes dynamically. Each row consists of three text boxes created using the same ID, all within an HTML table structure. var txtBox = "<input type='text' id='txtN ...

Maintain the div height as the image loads

Is there a way to prevent the collapse of the .img-container while an image is loading? Currently, when the image takes a few seconds to load, the container collapses and only expands to full height once the image has loaded. I would like the container to ...

Using Javascript to read a JSON string displayed in a URL

I'm working on developing a straightforward web application that extracts latitude and longitude data stored in a JSON format and places markers on a Google map based on this information. Currently, there is a program running on a server that generate ...

Declaring named exports dynamically in TypeScript using a d.ts file

I have developed a collection of VueJs components in TypeScript and I want to be able to use them globally in my Vue instance using Vue.use(library), or individually through named imports in Vue components. While everything functions correctly, I am facin ...

Error encountered: Unexpected token found while trying to import react-native-fetch-blob

We are facing an issue while trying to incorporate the react-native-fetch-blob package into our project using the code snippet below: const RNFetchBlob = require('react-native-fetch-blob'); const firebase = require('firebase'); Howeve ...

Encountering Issue: Exceeding the number of hooks rendered in the previous render cycle

Every time I load my Nextjs page, an error message displays: "Error: Rendered more hooks than during the previous render." I attempted to fix this by adding if (!router.isReady) return null after the useEffect code. However, this caused a problem where th ...

Issue with uppercase letters within a text input field

Imagine having an <input> and a <textarea> along with some JavaScript code that sends the value of the <input> to the <textarea> with additional text. How can you achieve this task? The text-transform: capitalize property is set in ...