CSS styling doesn't take effect until the page is reloaded due to the failure of cssText

After generating a new list item, it appears that the CSS styling is not being inherited until the page is reloaded. Even though I have added styling using cssText dynamically, it doesn't seem to be working as expected.

I've attempted using cssText and inline jQuery to apply the styles.

if (data.success) {
              console.log("Data success");
              // get the data that was returned.
              const contents = `${data.chatroom}`
              // create the dom tree under contacts
              const li = document.createElement('li');
              const div = document.createElement('div');
              const span = document.createElement('span');
              const div0= document.createElement('div')
              const p = document.createElement('p');
              const p0 = document.createElement('p');
              li.classList.add('contact');
              div.classList.add('wrap');
              div0.classList.add('meta');
              p.classList.add('name');
              p0.classList.add('preview');
              // setting innerHTML of new dom tree
              p.innerHTML = contents;
              div0.append(p);
              span.append(div0);
              div.append(span);
              li.append(div);
              var css = {"padding": "15px 0 30px 18px", "display": "block", "cursor": "pointer"};
              li.style.cssText = css;
              document.querySelector('#contacts').appendChild(li);

Despite my efforts, the newly generated list items are not reflecting the padding, display, and cursor styles dynamically as intended.

Answer №1

Issue lies in the fact that this is an object

let styleProperties = {"padding": "15px 0 30px 18px", "display": "block", "cursor": "pointer"};

However, cssText function requires a string input - a workaround would be:

li.style.cssText = "padding: 15px 0 30px 18px; display: block; cursor:pointer";

Answer №2

Greetings from Stack Overflow! In order to maximize your learning experience and receive more effective assistance, we recommend taking a look at . For example, consider simplifying your question by including only the essential components related to the issue such as:

  • Removing distracting elements like properly loaded data
  • Starting with the simplest case to address potential styling concerns before complicating the structure
  • Avoiding unnecessary details like classes that do not impact the outcome
  • Providing relevant context for better code testing and troubleshooting

const contents = "some text"

const li = document.createElement('li');
const p = document.createElement('p');

p.innerHTML = contents;
li.append(p);

const css = {"background": "red"};
li.style.cssText = css;

document.querySelector('#contacts').appendChild(li);
<div id="contacts"></div>

Upon running this code snippet, it's evident that the content is added correctly but lacks proper styling application. The discrepancy seems to lie within these lines of code:

const css = {"background": "red"};
li.style.cssText = css;

To simplify our query further, let's focus on:

const div = document.querySelector('#contacts')
div.innerText = "should be red"
div.style.cssText = {"background": "red"}
<div id="contacts"></div>

With fewer moving parts now, we can isolate the issue to

div.style.cssText = {"background": "red"}
, which fails to apply the desired style despite displaying the correct text. By researching the use of cssText, we uncovered detailed documentation at: https://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration

Text of type DOMString The parsable textual representation of the declaration block (excluding the surrounding curly braces). Setting this attribute will result in the parsing of the new value and resetting of all the properties in the declaration block including the removal or addition of properties.

In summary, the value should be a string resembling a .css file format rather than a JavaScript object. Applying this insight:

const div = document.querySelector('#contacts')
div.innerText = "should be red"
div.style.cssText = "background: red; padding: 20px;"
<div id="contacts"></div>

...yields the intended outcome! Simplifying your inquiry often uncovers the solution :)

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

Currently, I am utilizing Angular 2 to extract the name of a restaurant from a drop-down menu as soon as I input at least two characters

I am currently utilizing Angular 2 and I am trying to retrieve the names of all restaurants from a dropdown menu. Currently, when I click on the text field, it displays all the results, but I would like it to only show results after I have entered at least ...

Is there a way to retrieve the properties of another function within the same component?

I am trying to place NumberFormat inside OutlinedInput and I also need different properties for the format of NumberFormat. (There will be a select window that defines which format property to use). This is what I have: import OutlinedInput from "@ma ...

I am facing an issue with resolving services in my AngularJS controller

Having trouble resolving the service data in AngularJS controller. var kattaApp = angular.module('kattaApp', []).controller('kattaController', function($scope, dataFactory) { var promise = dataFactory.getResult().then(function(data ...

What are some ways to modify attributes in a jQuery datatable?

Upon loading the page, I initially set serverside to false. However, under certain conditions, I need to change serverside to true without altering any other attributes. For example: $(tableID).DataTable({ serverSide : false; }); Changing it to: $(t ...

I am attempting to adjust the color of the active tab, but I seem to be encountering issues in my code. Can anyone help me

The currently active tab should change along with the text inside the box, but it's not working as expected. I'm struggling to find out why. Here is a fiddle to demonstrate my progress so far: var btn1 = document.getElementById("btn1"); va ...

Can I bypass an invalid SSL certificate when making a request using a JavaScript library?

Is it possible to bypass invalid SSL certificates when using the widely-used request library? You can find more information about the library here: https://www.npmjs.com/package/request I am currently integrating this library into a Node.js server to send ...

Execute a function once all images have finished loading

My current approach involves utilizing a function to load images from an array: for (var i = 0; i < images_list.length; i++) { var img = new Image(); img.onload = function() { images_objects.push(this); ...

The Parse.com cloudcode refuses to enter the success or error state

Running this code in my Parse cloud, I noticed that when I call it from my app, it never enters the success or error statement. Could it be because the .save method isn't working? Any assistance would be greatly appreciated :) This is how I invoke t ...

Is there a way to ensure certain items are displayed on different lines?

Currently, I am working on styling an HTML list with the following properties: font-weight: bold; padding: 0px; margin: 0px; list-style-type: none; display: block; width:700px; font-size: 14px; white-space: pre-wrap; The individual cells within this list ...

Experiencing trouble with setting values in JavaScript?

I have my code set up to display numbers 170 and 122 using Javascript, but I'm not seeing the expected output. <!DOCTYPE html> <html> <body> <button onclick="UidToPost()">Get It</button> <script> ...

What is the best way to create vertical separators between CSS grid elements?

I currently have a grid with 3 columns and would like to add two vertical lines to separate the elements. To achieve this, I have placed two span elements between the grid elements using css styling. .vertical_line { position: absolute; height: 100%; ...

What is the best way to display multiple values in a single column in a datatable?

This function works effectively in rendering the code: { "data": "assignedTo", "render": function (data) { var btnDetail = "<a href='/Ticket/TicketDetail?ticketI ...

Tips for swapping a component with another component in React.js without the need for a page refresh

class Navigation extends Component { constructor(props) { super(props); this.state = { width: window.innerWidth, } } updateWidth = () => { if (this.state.width > 700) { this.setStat ...

Create tab title CSS design that coordinates with the tab content and features circular corners

I am currently working on creating html + css tabs with a unique design. The goal is to have the selected tab display the title connected to the tab content, with a "neck" rounding in like an arrow. After some progress, I have reached a point where the im ...

Obtain the key by using the JSON value

I am seeking to identify the recursive keys within a JSON Object. For instance, consider the following JSON Object: { "Division1" : { "checked": true, "level": 1, "District1-1": { "checked": true, "level ...

I attempted to install react-compare-image using npm, but encountered an error stating that the dependency tree could not be resolved

PS D:\skinprojecct> npm install --save react-compare-image npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email protected] npm ERR! Found: [email protected] npm ERR! node_mod ...

When interacting with elements with the "user-select: none" property, WkWebView still allows text selection

When using an iOS iPad app with a single fullscreen WKWebView, an issue arises when long-pressing on an area with user-select:none - the first text in the next available area without user-select:none gets selected instead of being ignored. Is there a way t ...

What could be causing my asynchronous JavaScript/Node.js function to bypass a significant portion of the code?

Upon calling the function below: async function sql_func(){ console.log('anothertest') async () => { console.log('third test') try { await sql.connect('heres the connection data') ...

Isotope: Real-time JSON content extracted from Google Spreadsheet

My goal is to populate an Isotope list using data from a Google Spreadsheet JSON. However, I'm facing issues with the animation and sorting functionality once I add the JSON. Although I have verified that the JSON/JavaScript for loading it works, I am ...

Utilizing a npm module in a web browser following importing in Node.js

I recently installed an npm module, but I'm having trouble figuring out how to use it in the browser after importing it. First, I installed the npm module using the following command (using a dummy example module): npm install sample-module In my p ...