The assigned javascript/CSS style is not being applied to every button

In an attempt to customize a list, I have written the following code:

<script>
for (n = 0; n < 3; n++) {
    var node = document.createElement("li");
    var btn = document.createElement("button");
    $("button").css({
        'background-color': '#CAC9DB',
        'width': '40px',
        'height': '40px',
        'font-size': '24px',
        'font-weight': 'bold'
    });
    var textnode = document.createTextNode(n);
    node.appendChild(btn);
    btn.appendChild(textnode);
    document.getElementById('list').appendChild(node);
}
</script>

However, I am encountering an issue where the CSS style for buttons is only applying to the first two buttons and not the last one. Can anyone explain why the last button is not being formatted according to the CSS style?

Answer №1

During each iteration of the loop, several actions take place:

  1. A new button is created
  2. The style of all buttons in the DOM is modified
  3. The newly created button from step 1 is added to the DOM

It's important to note that after adding the last button to the DOM, there's no need to restyle all buttons again.

To ensure that the most recently created button is styled correctly before being added to the DOM, replace $("button").css({ with $(btn).css({.


Using inline styles is generally discouraged, especially when the rules applied are not dynamic. Consider defining the styles for button in a CSS file instead. If you need specific styling for certain buttons, use $(btn).addClass('something') on those elements rather than globally styling all buttons.

Answer №2

Applying styles to all the button elements can be easily done using CSS rules.

button {
    background-color: #CAC9DB;
    width: 40px;
    height: 40px;
    font-size: 24px;
    font-weight: bold;
}

To style only newly created buttons, you can simply add a class to those buttons.

Javascript:

button.className = 'myButton';

CSS:

button.myButton {
    background-color: #CAC9DB;
    width: 40px;
    height: 40px;
    font-size: 24px;
    font-weight: bold;
}

Answer №3

If you want to style only the specific button instead of all buttons with jQuery, you can do so by creating each button individually:

for (n = 0; n < 3; n++) {
    var node = document.createElement("li");
    var btn = document.createElement("button");
    $(btn).css({
        'background-color': '#CAC9DB',
        'width': '40px',
        'height': '40px',
        'font-size': '24px',
        'font-weight': 'bold'
    });
    var textnode = document.createTextNode(n);
    node.appendChild(btn);
    btn.appendChild(textnode);
    document.getElementById('list').appendChild(node);
}

You can see an example here: http://jsfiddle.net/41Lk5xeo/

Alternatively, you can first add all the buttons and then style them collectively at the end:

for (n = 0; n < 3; n++) {
    var node = document.createElement("li");
    var btn = document.createElement("button");
    var textnode = document.createTextNode(n);
    node.appendChild(btn);
    btn.appendChild(textnode);
    document.getElementById('list').appendChild(node);
}

$('button').css({
    'background-color': '#CAC9DB',
    'width': '40px',
    'height': '40px',
    'font-size': '24px',
    'font-weight': 'bold'
});

Check out this example: http://jsfiddle.net/a5m0ehe6/

Answer №4

Insert the CSS styling code below

document.getElementById('list').appendChild(node);
.

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

Node.js tutorial: Fetching all pages of playlists from Spotify API

Currently, I am attempting to retrieve all of a user's playlists from the spotify API and display them in a selection list. The challenge lies in only being able to access 20 playlists at a time, which prompted me to create a while loop utilizing the ...

"Learn the trick to replace the Ctrl + N shortcut in Firefox and initiate an AJAX request

Note: The answer provided by Juan Mendes has been selected as the best answer for my situation due to its usefulness. AxGryndr also offered valuable information, so I recommend reading both answers as they are beneficial in different scenarios. Thank you t ...

Ways to maneuver the vehicle by using the left or right key inputs

I am a beginner with canvas and game development. I am currently working on a project where a car moves in a straight line, but I want to add functionality for the car to turn anti-clockwise when the left key is pressed, and clockwise when the right key is ...

What is the best way to adjust the width of a table td element using CSS in Spiceworks?

I'm attempting to modify a CSS code snippet for Spiceworks. Here is the specific line that I need to adjust: <td class="body-id cell-id" style="width: 12%; "></td> The following code: SPICEWORKS.utils.addStyle('body{background-col ...

Upon initialization, my data is not being rendered by componentDidMount, instead, it is only displayed during

As a newcomer to React, I am aware that there may be a more efficient way to accomplish this task. Currently, I am trying to display all events associated with a specific group by passing the group's ID as a prop to the Events component. The Events co ...

Adapting iFrame height to accommodate fluctuating content height in real time (details included)

I have an embedded iframe that contains a form with jQuery validation. When errors occur, the content height of the iframe increases dynamically. Below is the script I use to adjust the height of my iframe based on its content: function doIframe(){ o = d ...

A JavaScript AddEventListener will not execute a function that has parameters

Attempting to execute a function with two parameters in NuxtJS upon clicking an element using AddEventListener. async handleSubmit(recipe, userRating) {some code...} setup(recipe) { document.querySelectorAll('.recipe-rating > .star').forEac ...

Issues with Angular service functionality

I've been working on an application using Angular for the client side and Node for the server side. I've incorporated some API's into my Angular code, but I'm encountering difficulties with retrieving data from a specific API. Can someo ...

Generate an array that can be accessed across all components

As someone new to reactjs, I'm trying to figure out how to handle an array of objects so that it can be global and accessed from multiple components. Should I create another class and import it for this purpose? In Angular, I would typically create a ...

Change the UTC DateTime received from the server to the Local DateTime displayed on the web page

In my Sql database, I have a column storing values as UTC in a DateTime field. The requirement now is to convert this UTC into Local Time based on the geographical location of the User accessing the report. I am aware that using ToLocalTime() will achieve ...

Is it possible to have 2 images side by side?

I am attempting to combine these two images to create a map. Here is an illustration of how they should fit together. https://i.sstatic.net/zGZgS.png var testHeightMap = 'x\n' + 'x'; var myCanvas = document.getElementById( ...

Organizing dates with Javascript

Is there a way to convert a string from this format : 2014-06-12T23:00:00 To another format using JavaScript, like so : 12/06/2014 23:00 ...

JS-powered menu links losing color after being clicked

I have a JavaScript rollover switch issue - when I click on the link, the color should stay orange (#f7931d), but it reverts back to grey. What am I missing in my code? CSS: #content-slider { padding-top:5px; height: 240px; width: 359px; ...

Enhancing TypeScript with Generic Proxyify Functionality

I'm attempting to enclose a basic interface provided through a type generic in order to alter the return value of each function within the interface. For instance: interface IBaseInterface { test(a?: boolean, b?: number): Promise<boolean>; ...

My attempt to deploy the Github website resulted in a blank screen appearing

Hey there, I've been working on coding a website and trying to publish it using Github. However, every time I deploy it, the page shows up blank. Here is the link to my repository: https://github.com/bbravoo/bbravoo.github.io-. Any help would be great ...

What could be causing the TypeError that is preventing my code from running smoothly?

I can't seem to figure out why I'm constantly encountering the error message Cannot destructure property 'id' of 'this.props.customer' as it is undefined.. Despite double-checking my code and making sure everything looks corre ...

Achieving overlapping div layouts with CSS styling

Displayed above are 4 different divs: red, green, and blue. I am seeking to have the blue div positioned directly below the green div, which contains the text "JACKSON". Additionally, I do not want the green div to expand beyond its content, nor do I want ...

Centering items in Material UI Grid

I'm currently grappling with understanding Material UI's grid system and implementing it in React.js, and I find it a bit perplexing. My goal is to center the spinner loader and text irrespective of viewport size. While I can manage to place the ...

Displaying images within a table using innerHTML (Javascript / Html)

Let's start off with some important details: I have a dynamic table that is being generated. The structure of the table is as follows: |item__ | price | category | category | category | category | picture | |chicken| $20 | _______ |_ ______ ...

Multiple subscriptions to a Typescript service in an AngularJS controller have caused an issue with unsubscribing from it

Issue at Hand: I am currently working on merging AngularJS with Angular by creating components and services to be used within an AngularJS controller. The AngularJS Controller is initiated through $routeProvider. One of the components I have created is a ...