fstopzero
fstopzero

Reputation: 1073

Add class to dynamically generated element with css

I suspect this isn't possible, but am looking for confirmation. I have a series of image elements that are added as id's to a div. I'm trying to attach another small image to the first one. Because the container varies in width based on the user's game content, attaching it to the container hasn't yielded consistent results. My image is stored as a class in the main css file.

Is there a way to use ::before to attach a class to an element that is dynamically generated?

I'm deeply discouraged by my manager from using an javascript for this particular task.

Many thanks.

Upvotes: 0

Views: 1212

Answers (3)

Stickers
Stickers

Reputation: 78686

I don't think you can add a class name with CSS, but you can just use selector:pseudo-class for it, example below, to use .container:before as a real class name.

.container:before {
    content: url("http://lorempixel.com/50/50");
}
<div class="container">
    <img src="http://lorempixel.com/100/100" />
    <img src="http://lorempixel.com/150/150" />
</div>

Fiddle Demo: http://jsfiddle.net/dh6ynq32/ (with some custom styles)

Upvotes: 1

Aaron
Aaron

Reputation: 10440

You can't add a class using css....

But you could use the :before psuedo to show the image you're trying to add.

div#this-id {
  position: relative;
  width: 300px;
  height: 200px;
  background: blue;
}
div#this-id:before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 50px;
  height: 200px;
  background: url(image-folder/image/jpg) no-repeat 0 0 #f00;
}
<div id="this-id"></div>

Upvotes: 2

Jules
Jules

Reputation: 295

You can use in jQuery something like $( your_element ).addClass( your_class)

Upvotes: -1

Related Questions