What is preventing me from changing the text color of this span element to white?

For some reason, I'm trying to make the first two texts of each line appear in white, but my CSS doesn't seem to affect the span elements generated by JavaScript. Take a look at the code snippet below for more details.

I'm still learning how to navigate Stack Overflow, so please bear with me. I have included the code snippet below.

export default {
  mounted(){
    console.log("Hello!")
    let list = document.querySelectorAll('.shinchou-menu li a')
    list.forEach( link => {
      let letters = link.textContent.split("");
      link.textContent = "";
      letters.forEach((words, i) => {
        let span = document.createElement("span");
        span.textContent = words
        if(i < 2){
          span.className = "highlight"
        }
        span.style.transitionDelay = `${i/10}`
        link.append(span);
      })
    })
  }
}
<style>
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #fafafa;
}
</style>

<style lang="less" scoped>
.shinchou-menu {
  --heightlight-text-color: #00ACF0;
  list-style: none;

  li {    
    a {
      text-decoration: none;
      display: inline-flex;
      background: #000;
      font-size: 1.6em;
      font-weight: 700;
      color: var(--heightlight-text-color);
      padding: 4px;
      margin: 6px 0;
  
      span.highlight {
         color: #FFF;
      } 
    }
  } 
}
</style>
<template>
  <div>
      <ul class="shinchou-menu">
        <li><a href="#">ニュース</a></li>
        <li><a href="#">ストーリー</a></li>
        <li><a href="#">スターフ&キャスト</a></li>
        <li><a href="#">キャラクター</a></li>
        <li><a href="#">放送·配信情報</a></li>
      </ul>
  </div>
</template>

Answer №1

Avoid direct manipulation of the DOM!

Vue maintains a separate virtual DOM structure to monitor all elements for reactivity. Whenever a reactive change occurs, the corresponding DOM node on the actual page is re-rendered. This approach is faster than tracking changes directly in the DOM.

Changing the DOM directly will result in the loss of modifications when Vue re-renders.

The recommended approach is to manage your data within the component and let Vue handle rendering using template structural directives (v-if, v-for, etc...).


In your particular scenario, the implementation would look something like this:

Vue2:

new Vue({
  el: '#app',
  data: () => ({
    items: [
      'ニュース',
      'ストーリー',
      'スターフ&キャスト',
      'キャラクター',
      '放送·配信情報'
    ]
  })
})
.highlighted { color: red }
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5d2b28381d6f737b736c69">[email protected]</a>"></script>
<div id="app">
  <ul>
    <li v-for="item in items"
        :class="{ highlighted: item.split('·').length > 1 }"
        v-text="item" />
  </ul>
</div>

Vue3:

Vue.createApp({
  setup: () => ({
    items: [
      'ニュース',
      'ストーリー',
      'スターフ&キャスト',
      'キャラクター',
      '放送·配信情報'
    ]
  })
}).mount('#app')
.highlighted { color: red }
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="app">
  <ul>
    <li v-for="item in items"
        :class="{ highlighted: item.split('·').length > 1 }"
        v-text="item" />
  </ul>
</div>


Note: It's recommended to create a method that accepts the item as a parameter and returns the appropriate classes for the item. This approach eliminates the need to include JavaScript logic within the template.

<li v-for="item in items" :class="itemClasses(item)">

component:

/* Options API syntax: */
methods: {
  itemClasses(item) {
   /* return string, array of strings, or class object
      docs: https://vuejs.org/guide/essentials/class-and-style.html
    */
  }
}

/* (alternative) Composition API syntax : */
setup() {
  // replace this function with your own logic
  const itemClasses = item => item.split('·').length > 1;

  return { itemClasses }
}

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

Bootstrap creates a small and calculated width for elements

Currently, I am integrating the react-datepicker plugin into my project alongside Bootstrap 3. Upon implementation, I have noticed that the size of the datepicker on my website appears to be smaller than the examples provided in the plugin demos. It seems ...

Creating a triangle shape using Bootstrap to style a div element, similar to the image provided

Trying to achieve the look of the attached image with a few divs. I know I can use a background image like this: background:url(image.png) no-repeat left top; But I'm curious if there's another way to achieve this without using a background ima ...

How come TinyMCE is showing HTML code instead of formatted text?

I have been working on integrating TinyMCE with React on the frontend and django(DRF) on the backend. After saving data from TinyMCE, it retains the HTML tags when displayed back, like this: <p>test</p> <div>Test inside div</div> ...

What causes the width of unrelated cells to change when the contents of colspan'd cells expand in IE7?

Before we delve into the details, I invite you to take a look at this fiddle using IE7. It's quite intricate and not something I want to repeat here. The main issue is that clicking on the red block should display additional information. The top row ...

How can I turn off eslint validation in my Vue project?

I have a question about my configuration in vue.config.js. I've tried setting it as follows: module.exports = { lintOnSave: false } However, the changes don't seem to take effect. Can anyone provide guidance on how to disable eslint validati ...

Unexpected issue with sliding menu toggle implementation

I have been struggling to make a menu slide to the left when a button is clicked, and then slide back to its original position when the same button is clicked again. Although I have been using the toggle method, it doesn't seem to be working for me. I ...

Ways to halt a CSS animation when it reaches the screen boundary

I put together this demo: By clicking, a red box falls down. The issue arises when trying to determine the screen size using only CSS. In my demo, I set the box to fall for 1000px regardless of the actual screen height. Here is the keyframe code snippet ...

How to upload an image using Java and store it on a server without the use of Html5

Looking to upload an image file on the server using a servlet without utilizing HTML5. While browsing through stackoverflow, most answers I found were based on PHP. I attempted to read the image file at the client-side in JavaScript with FileReader.readAsD ...

Modify the class's height by utilizing props

Using Vue 3 and Bootstrap 5, I have a props named number which should receive integers from 1 to 10. My goal is to incorporate the number in my CSS scrollbar class, but so far it's not working as expected. There are no error messages, it just doesn&a ...

What is the best way to include an API key in the response to an Angular client application?

I'm working on transferring my API key from NodeJS to an Angular client application using $http, but I am unclear on the approach. Below is a snippet from my NodeJS file: // http://api.openweathermap.org/data/2.5/weather var express = require(' ...

Can a TypeScript-typed wrapper for localStorage be created to handle mapped return values effectively?

Is it feasible to create a TypeScript wrapper for localStorage with a schema that outlines all the possible values stored in localStorage? Specifically, I am struggling to define the return type so that it corresponds to the appropriate type specified in t ...

Having Trouble Parsing JSON Object with JQuery?

I'm having trouble extracting data from a valid JSON object using jQuery/JavaScript - it always returns as 'undefined'. var json = (the string below). var obj = $.parseJSON(JSON.stringify(JSON.stringify(json))); alert(obj); // aler ...

Customizing jquery mobile styling

I am dealing with a table where the challenge lies in aligning the text to center in the header. .info-header { font-size: small; text-align: center; } Despite setting the alignment, the row still inherits left alignment from jQuery mobile. Seeking ...

Adjust the transparency of CSS elements using a jQuery selector

I am developing a grid of brand thumbnails with interactive icons. When one of the icons is hovered, I want all the icons to change opacity and become visible. Here is the current HTML structure: <div id="brands-wrapper"> <img class="brands" ...

Choosing the initial tab to display when the page loads from a selection of 3 tabs

How can I set the "All" tab to be selected by default when the page loads, with the text color black and underlined? .publisher-tab { background-color: rgb(255, 255, 255) !important; color: #B3B3B3; font-family: 'Open Sans'; font-style ...

Applying flexbox to create a visually appealing design

Is there a way to achieve this layout using flexbox without relying on grid due to limited support in IE11? I want to be able to easily add or remove small divs without adding more containers. To see the desired layout, check out this image: Desired Layou ...

Error message: The "spawn" function is not defined and is causing a TypeError to be thrown in

Having a bit of trouble here. I'm trying to make an async request using redux-thunk in my action creator, and the code looks like this: export const downloadFromYoutube = (download) => { console.log("Hello"); return dispatch => { va ...

What is the best way to modify the URL path to eliminate a specific parameter?

Recently, I integrated authentication into my Vue.js application utilizing Amazon AWS Cognito. Although the authentication is functioning properly, I am looking to tidy up the URL and so far have not been successful in doing so. Following authentication w ...

What could be causing my node server's REST endpoints to not function properly?

Here is a snippet of my index.js file: var http = require('http'); var express = require('express'); var path = require('path'); var bodyParser = require('body-parser') var app = express(); var currentVideo = &apos ...

The image placeholder is missing

This is my custom Results component: This is my custom Thumbnail component: `import React from "react"; const Thumbnail = ({ result }) => { return ( <div> <h1>Thumbnail</h1> </div> ); }; export default Thumb ...