Struggling to target specific elements in CSS that are dynamically generated through JavaScript

After using JavaScript to generate some divs, I ended up with the following code:

const container = document.querySelector('#container');
for(let i = 1; i < 17; i++) {
    var row = document.createElement('div');
    row.id = 'r' + i;
    row.class = 'row';
    container.appendChild(row);
    for(let j = 1; j < 17; j++) {
        var newDiv = document.createElement('div');
        newDiv.id = 'c' + j;
        newDiv.class = 'box';
        newDiv.textContent = row.id;
        row.appendChild(newDiv);
    }
}

Attempting to style the row divs by adding a green border using CSS:

#row {
    border: 1px solid green;

}

Why are the rows not displaying with a green border? Can CSS target elements created dynamically in JavaScript?

I expected 16 boxes for each of the 16 div elements with class "row".

Answer №1

  1. Instead of using class in JavaScript, make sure to use className.
element.className = 'element'
  1. When writing CSS, remember to use . for classes instead of # for ids.
.element {
  background-color: purple;
}

Answer №2

There are two issues at play here...

The first problem lies within the realm of CSS. In order to apply styles to a class in CSS, you need to use the . selector. So, to target the row class and give it styling, you should do the following:

.row{
    border: 1px solid green;
}

The second issue pertains to JavaScript.

JavaScript does not have a class property for DOM elements. Instead, it offers two other options for working with classes. The first is the className property, which is a string that you need to handle manually when making changes.

Here is how you would use it:

row.className = 'row'

The second option is the classList object, which provides useful methods like add, remove, and contains to easily manipulate classes in JavaScript.

In your case, you would do this:

row.classList.add('row')

To remove the class, you can simply use:

row.classList.remove('row')

And if you need to perform actions based on the presence of a class, you can check for it using:

if( row.classList.contains('row') ) {
    // Your code here
}

I hope this information proves helpful.

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

AngularJS date and time picker featuring user-defined input validation

Is there an AngularJS component available that offers both a date/time picker and the ability to input dates using the keyboard? ...

Integrating dual Google Maps onto a single HTML page

I'm facing an issue with implementing two Google maps on a single page where the second map seems to be malfunctioning. Below is the code I am currently using: <style> #map-london { width: 500px; height: 400px; } #map-belgium { wi ...

Looking for guidance on how to specify the angular direction in the ng-repeat

I am facing a challenge with the structure of my ng-repeat directive and I am having trouble navigating through it. Here is a representation of the data in array format JSON style {"data":[ ["sameer","1001", [ {"button_icon": ...

The sequencing of operations in Node.js streams

I am having an issue with validating an image before saving it to disk. Currently, I am utilizing the GM library. // Express application implementation app.post('/image', function(req, res) { var stream = gm(req) .size({ bufferStr ...

Is it possible to adjust the timezone settings on my GraphQL timestamp data?

I've come across a lot of helpful information regarding the usage of Date() and timezones, but something seems to be off. In my GraphQL setup (sourcing from Sanity), I have configured it to use formatString in this manner: export default function Minu ...

Exploring Next.js: Leveraging fetch to retrieve data in getServerSideProps and passing it to the client via query parameters

I'm utilizing a getServerSideProps function on the directory page. pages/catalog/index.js export async function getServerSideProps(ctx) { const response = await fetch( `http://someDomen.com/api/ipro/catalog?${ctx?.query?.page ? `page=${ctx.quer ...

Is there a way to distinguish mouseout/leave events based on the side in jQuery?

How can I detect if the mouse event has moved away from a particular side of an element? For example, I have a DIV with a mouseover/mouseenter event and I only want to activate the action when the mouse leaves from the left or right side of the DIV. If it ...

Updating database through AJAX calls does not work

I'm currently developing a system that requires the ability to remove employees from their Saturday shifts. This process involves clicking on an icon that triggers the JavaScript function "removeEmpFromSaturday" and passes relevant parameters. Within ...

Is there a way to access a child component's method from the parent component using ref in Vue3?

I am encountering an issue while attempting to call the child method from the parent component in vue3 using the ref method. Unfortunately, an error is being thrown. Uncaught TypeError: addNewPaper.value?.savePaper is not a function Displayed below is m ...

Error: An unexpected identifier was encountered while executing my function

I've been trying to implement a function that I found online, but when I try to run it in the terminal, I keep getting this error: /home/simone/gekko/strategies/high.js:10 sma: function(name, price, points) ^^^ SyntaxError: Unexpected identifier I ...

Responsive issue identified with Bootstrap navbar hamburger menu upon clicking

My website has an issue on mobile where the hamburger menu appears but doesn't respond when clicked. I'm unsure what's causing this problem in my code. <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a ...

Always make sure to call for files using their respective names in

Here is how my project structure looks like: . ├── node_modules ├── package.json ├── www │ ├── css │ ├── js │ ├── file.js │ ├── folder │ ├── file2.js │ ├─ ...

Can we iterate through an array containing arrays of objects in a loop?

Here is an example of how I want my solution to appear: https://i.sstatic.net/B9AW1.png Currently, I have created an array where I group items by their first letter, like this: const grouped = _.groupBy(topicPages, key => key.relatedTopic.title[0]); ...

Managing spinners in Protractor when they are concealed by a wrapper element

While writing a test for an Angular app using Protractor, I encountered several issues with handling spinners. I managed to solve some of them, but I'm unsure how to test spinners that are hidden by a wrapper. For instance, when the parent tag has ng- ...

Having trouble utilizing the DatePicker component in my react native application

I've encountered an issue while using DatePicker in react native. Whenever I try to use it, an error pops up saying: "render error a date or time must be specified as value prop". Here is the link to my repository: my github repository const [date, se ...

Passing the title of a page as data to a component in Next.js

I am currently working on setting a custom title for each page within my next.js project. Here is an example of a simple Layout: const MainLayout = props => { return ( <Layout style={{ minHeight: "100vh" }}> <Head> < ...

bootstrap3 container alignment

I encountered a challenge while attempting to right-align multiple Bootstrap 3 containers in a straightforward manner. Despite my efforts, achieving this proved to be more complex than expected. In essence, I faced an issue where aligning the text box with ...

The CSS Menu is not displaying correctly on Internet Explorer 8

My horizontal menu appears distorted on IE8 (and possibly older versions) as shown in the first image. However, there are no issues with the latest versions of Safari, Firefox, and Chrome as depicted in the second image. Any suggestions on why this is happ ...

How can I use map functions to change the border color of specific items when clicked?

I have an array filled with various data. Here is how my Array looks like, const faqData = [ { q: "How Can We Help You?", a: "Find answers to our most frequently asked questions below. If you can't find what you need, pl ...

Tips for aligning the dropdown menu to start from the border of the menu bar instead of displaying directly below the text

I have designed a menu-header section for my website, inspired by this image. I created a fiddle to showcase it. However, I am facing an issue where the dropdown elements for "PROGRAMS" and "WORLD OF NORTHMAN" should start from the border of the header ins ...