Elements that are added dynamically will not inherit the correct CSS styles, requiring JavaScript to style them properly

My <ul> element dynamically adds <li> elements, and I am attempting to make the first <li> wider at 63% while the others are at 60%. However, the first one is only getting a width of 60%. Any thoughts on why this might be happening?

I need to achieve this using Javascript only, without utilizing a CSS file.

Below is the code snippet:

$('.list').css({
  listStyle: 'none',
  padding: '0',
  height: '100%',
  overflowX: 'scroll',
});

$('.item-wrapper').css({
  background:'#FFFFFF',
  width: '60%',
  margin: '5px',
});

$('.item-wrapper').first().css({
  width:'63% !important',
});

Edit: I forgot to include the resulting markup, here it is:

<ul class="list" style="list-style: none; padding: 0px; height: 100%; overflow-x: scroll;">
  <li class="item">
    <div class="item-wrapper" style="width: 60%; margin: 5px; background: rgb(255, 255, 255);">
        <img class="thumbnail" src="images/frame_0001.png" alt="tumbnail" style="width: 25%;">
    </div>
  </li>
  <li class="item">
    <div class="item-wrapper" style="width: 60%; margin: 5px; background: rgb(255, 255, 255);">
        <img class="thumbnail" src="images/frame_0002.png" alt="tumbnail" style="width: 25%;">
    </div>
  </li>
</ul>

EDIT 2: I attempted rearranging the order of the .css() functions but it did not resolve the issue.

Answer №1

The reason behind the issue lies in your overuse of !important; you should eliminate it.

Try this modified code:

$('.item-wrapper').first().css({
  width:'63%',
});

Aside from that, your syntax is correct. Your approach may be unconventional, but it seems necessary due to external CSS requirements.

To delve deeper into jQuery's conflict with !important, check out this link:

IMPORTANT: Now that you've removed precedence manipulation, remember that script order matters! If you rearrange your javascript so the width is set to 63% before setting it to 60% elsewhere, it will stay at 60%.

Answer №2

consider rearranging them

$('.item-wrapper').css({
  background:'#FFFFFF',
  width: '60%',
  margin: '5px'
});

$('.item-wrapper').first().css({
  width:'63% !important'
});

Just keep in mind that when you select your .item-wrapper elements and apply the styles, it may not affect elements added to the ul later on

Answer №3

you should consider putting it in a function

    $(document).ready(function(){
$('.list').css({
  listStyle: 'none',
  padding: '0',
  height: '100%',
  overflowX: 'scroll',
});

$('.item-wrapper').first().css({
  width:'63% !important',
});

$('.item-wrapper').css({
  background:'#FFFFFF',
  width: '60%',
  margin: '5px',
});
    })

Check out the JSFIDDLE link here

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

Exploring different methods for drawing a polygon by iterating through JSON values

I am attempting to automatically draw a polygon using values stored in a database. The Python file I have returns JSON results to an AJAX call. In the AJAX success section, I need to iterate through the JSON data and automatically draw a polygon on a Googl ...

Like button for Facebook located at the bottom of a static webpage

I am facing an issue with my web application where it does not scroll properly, especially when there is a Facebook button at the bottom. The behavior in Chrome and Firefox is inconsistent and causing some trouble. In Chrome, the div repositions correctly ...

Error message in Ionic 2: "Property is not found on type"

Currently, I am working on a project in Ionic 2 and have encountered a stumbling block with a seemingly simple task. My issue lies with a Textbox where I aim to input text that will then be displayed. I found some code on a website (http://www.tizag.com/j ...

Typescript and Mongoose Schema - Common Design Mistakes

I am encountering two issues while defining a schema using mongoose and typescript. Below is the code snippet I'm having trouble with: import { Document, Schema, Model, model} from "mongoose"; export interface IApplication { id: number; name ...

Unveiling the Quirk of Foundation 5: Grid Encounters a Popping

Recently, I encountered an issue with Foundation 5. Whenever I attempt to apply the "position:fixed" property on a "div" element that is part of the Foundation Grid, it causes the div to break out of the grid and align itself with the left edge of the ro ...

If the server goes offline, it will not produce an error message

Running a factory in AngularJS angular.module('app.services',[]) .factory('myFactory', function($http){ return { getData: function(){ return {animal: 'dog'} }, isUser: function() ...

`Trick Ajax into displaying 200 status code even on error responses`

Is it possible to suppress exceptions in the console by manually setting the status code to 200 for all errors? For example, can I change a 500 internal server error response to 200? Although I understand that hard-coding status codes is generally conside ...

What could be the reason the server actions in nextjs 13 are not functioning correctly?

I am currently working on a project to retrieve data from mockapi.io, a mock API. However, I am encountering an issue where the fetched data is not displaying in the browser. There are no visible errors, and the browser window remains blank. Interestingly, ...

Tricky problem with z-index - how to position a CSS3 triangle under the menu

Hey there, thank you for taking the time to look into my issue. I'm currently working on a menu design that I would like to resemble this example: The key feature here is creating triangular shapes on either side and positioning them beneath the men ...

Designing a layout with one box on top and two beneath it, covering the entire page, can be achieved by following these steps

https://i.sstatic.net/A1eUh.png I am currently working on a project where I want to divide the screen into three sections. One section will cover half of the screen to display an image slider, and the remaining half will have two sections which is already ...

Troubling inconsistency in jQuery's .css function performance

I'm facing a problem with the jquery .css function. I am using it to retrieve the actual height of elements that have their height set to auto. The code I am currently using is as follows: $(this).css({ height: $(this).css("height"), width: $(this).c ...

Implementing JQuery animation to dynamically change the image source attribute

Greetings! I have been working on a project for quite some time now, attempting to create a fullscreen background slideshow using jQuery. While I successfully implemented it with CSS animations, I encountered lagging issues when switching tabs and returnin ...

Is it secure to store the access token within the NextAuth session?

Utilizing a custom API built with Node.js and Express.js, I have implemented nextAuth to authenticate users in my Next.js application. Upon a successful login, the date is stored in the nextAuth session and can be accessed using the useSession hook. To acc ...

What could be causing this program to continuously add values to the message table whenever the page is refreshed?

Looking for a simple chatting system using php, mysql, html, css and javascript? Check out this code snippet. However, there seems to be an issue with the message sending functionality. Every time a user sends a message and refreshes the page, the same m ...

What is the best way to select a random array entry in PHP?

I am currently working on developing a website to enhance my programming skills. <html> <title>VidSelector</title> <head> <link rel="stylesheet" type="text/css" href="styles.css"> <div id="welcome" ...

Tips on choosing filters and leveraging the chosen value for searching in a Vue application

I am currently working on a Vue JS application that allows users to apply filters and search a database. The user can select or type in filters, such as "to" and "from", which are then used in a fetch URL to retrieve data from a json-server. Once the user ...

What is the best way to generate a JSON output that contains the entire

The use of {foo|json} is effective for displaying only part of the $scope. Is there a way to pass the entire scope to the json filter? ...

I need help figuring out how to handle click events when using VueJS 2.0 in conjunction with a vue-mdl menu component

While @click doesn't seem to respond, v-bind:click does register. However, I'm facing the challenge of not being able to access the mdl-menu or mdl-menu-item components in order to add the method. The goal is to implement something like @click=" ...

Guide on enabling users to input slide number and URL address to load content using Ajax

Is there a way to customize the number of slides in a slider and choose which content is loaded into each slide using AJAX calls in jQuery? Currently, my slider uses the jQuery .load() method to dynamically load content into each slide when it becomes vis ...

Verify if the user is currently inputting text within a specific range of characters within

I am dealing with a specific issue involving a textarea. By default, this textarea contains a string of any type, but a user is only able to type inside opening and closing brackets. For example, "Leave[]" allows typing within the brackets but not outsid ...