Applying CSS Style to Element Created in a Vue Component

<template>
  <div id="body">
    <button type="button" @click="create">Create</button>
  </div>
</template>
<script>
  export default {
    methods: {
      create () {
        let e = document.createElement('input');
        e.classList.add('input-test');
        e.setAttribute('type', 'text');
        e.setAttribute('value', 'test');
        document.getElementById('body').appendChild(e);
      }
    }
  }
</script>
<style scoped>
.input-test {
  color: red;
}
</style>

This piece of code was my attempt to add the input element with a specific style class called input-test. However, I encountered an issue where the style defined in the .input-test class wasn't applied to the element itself. Curiously enough, it worked when I removed the "scoped" attribute from the style tag. Can anyone explain why this happened?

Answer №1

My solution involved utilizing deep selectors learn about deep selectors

Answer №2

The answer I was looking for can be found at this link:

To include the scoped css identifier in the created element of createElement, you can use the following code:

e.setAttribute(this.$options._scopeId, '');

Answer №3

When examining vue's approach to handling style scoping, you'll notice that each element receives a unique identifier for its scope, which is then incorporated into your scoped CSS. However, any new elements created won't undergo the Vue transpilation process and therefore won't receive the necessary scoping identifier.

If you only want an element to display when a button is clicked, you can add it to the DOM and reveal it upon click using the v-if directive

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

Navigating through a table with dynamic entries fetched from JSON using pagination

I am working on a page that dynamically fetches data from a JSON file and displays it in a table format. The JavaScript code I've written currently retrieves all entries at once, but I want to implement pagination with 10 entries per page as well as s ...

What are the steps to enable a Vue component to handle its own transitions?

I am looking for a way to handle enter and leave animations in Vue when components are mounted or removed. My goal is to consolidate all the animation code into its own component for better organization. <template> <transition @enter="enter" ...

Exploring the depths of Rx.ReplaySubject: Techniques for delaying the `next()` event

Confused Mind: Either I'm mistaken, or the whiskey is starting to take effect. (I can't rule out the possibility that I'm just going crazy. Apologies for that.) Assumption: My assumption was that ReplaySubject would emit a single value eve ...

unable to locate a path while defining routes in a distinct file

I am encountering an issue with my localhost server. When I enter the URL localhost:8000, it correctly displays a message in the browser saying "hello world". However, when I try entering localhost:8000/product, it does not find the correct path. Server.j ...

Exploring the focus() method of refs in Vue 3

I'm struggling to comprehend why my straightforward test case keeps failing. As I delve into the world of testing in Vue, I've created a simple test where the element.focus() is triggered onMount(() => /* see implementation ...

How to find a collision between a spherical object and a triangular shape in a three

In my research, I am exploring the possibility of detecting collisions between a triangle and a sphere in three.js. Currently, I have devised a method using the raycaster and the sphere's vertices. However, this approach has proven to be unreliable a ...

The background color is not extending to the edges of the row or column

After making adjustments to the layout of a specific section on my webpage by adding rows and columns, I noticed a blank strip where the background color fails to fill in. The rows within this section are contained within a div class called container-fluid ...

Populating the Join Table with Information

I have a scenario involving two models, Contact and Message, with a join model named ContactMessage. Contact.belongsToMany(models.Message, { through: 'ContactMessage' }) Message.belongsToMany(models.Contact, { through: 'ContactMessage& ...

VueJS implementation of the Navbar Toggler Bootstrap that closes on click outside using a directive

Is there a way to close the Bootstrap-VueJS toggle navbar easily when clicking outside? I have attempted various directive codes, experimented with the vue-click-outside plugin, and tried different examples but haven't had any success. It appears tha ...

Ensure that the Div element is able to wrap lines in the same way that the Span element

Is there a method to ensure that a div element wraps the lines similar to how a span does? JSFiddle for testing In this example, I utilized the span tag to create an appearance as if the text was highlighted by a yellow highlighter pen. Everything functi ...

"Implementing a jQuery dialog box that sends JSON response to a different page rather than the current

Currently, I am working on an MVC application where I need to insert properties of certain objects. To achieve this, I have created a modal popup using jQuery dialog. In order to avoid any interference with other user actions, I have implemented an Ajax.Be ...

Running the test suite in another tab is causing it to fail

I am experiencing an unusual issue in my protractor UI test. During one of the tests, I need to click on a link that opens in a new tab. The test passes when run individually, but fails when run as part of the test suite. I would appreciate it if you coul ...

hover-triggered keyframe animation

Recently, I've been experimenting with CSS keyframe animation using the code below: .pulse-animation { margin: 50px; display: block; width: 52px; height: 52px; border-radius: 50%; background: #ff8717; cursor: pointer; animation: pul ...

Encountered a JavaScript error when trying to trigger an alert using PHP

I've incorporated fusion maps into one of my applications. In a particular example, I need to transfer values from one map to another chart, However, I encountered an issue where if the data passed is numeric, the alert message displays correctly, b ...

An issue arose when attempting to run vue-cli-service build or npm run build on a shared hosting platform, resulting in an error related

Encountering an error when attempting to build my Vue project on a shared hosting service: Interestingly, running npm run build on my local environment results in success. Error Description: Building for production.../home/intechpe/onlineku-admin/n ...

Issue with Bootstrap affix reset not functioning properly

I've been working on implementing a responsive affix in Bootstrap, and I'm facing some challenges. When the page gets resized, certain elements hide at the top of the page. Due to these width changes, I need to reset the affix and adjust it to th ...

Using React and Redux to update a property in the state with a modified array

I am currently developing a React app and utilizing Redux for state management. Below is the code snippet I am working with: menu.actions.js: import { apiUrl, apiConfig } from '../../util/api'; import { ADD_CATEGORY, GET_MENU } from './men ...

"Troubleshooting a problem with Mongoose's findOne.populate method

There is an array of user IDs stored in the currentUser.follow property. Each user has posts with a referenceId from the PostSchema. I am trying to populate each user's posts and store them in an array called userArray. However, due to a scope issue, ...

Vue app running on node server with IIS gives 404 error: page not found

Running a Vue app on a node server and trying to implement a URL redirect using IIS has resulted in a puzzling issue. Everything works perfectly fine when the app is accessed locally with the specified port: https://i.sstatic.net/5bfBu.png However, upon a ...

Having trouble retrieving the content of a DIV using JavaScript? Can't get .innerHTML to work?

Currently, I am working on a jQuery drag and drop feature and aiming to save the final outcomes in a database. My approach involves utilizing JavaScript to extract values, but I seem to be encountering an issue where 'NULL' is returned instead of ...