Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying styles from CSS to newly appended elements

I add an element to a parent div dynamically.

$('.some_div').append("<li class="hi">hey!</li>")

In my CSS,

.hi {
  color: white;
}

However, since <li class="hi"> is dynamically added, it seems the styles defined in CSS are not applied to the element. So,

$('.some_div').append("<li class='hi'>hey!</li>")
$('li.hi').css({"color":"white"});

would actually do the trick, but it seems redundant to me as the style is already defined in CSS file. Is this the only way to do it?

Update:

$('.some_div').append('<li style="color:white" >hey!</li>')

The above will work, but since the style is already defined in a separate CSS file, it'd be still redundant. My question was if there is a way to avoid this redundancy.

in CSS,

.some_div > li {
  font-size: 20px;
  background-color: 30px;
  margin-right: 2px;
}

.hi {
  color: white;
}

All of this won't be applied when I add a new element via ($).append(), so I am asking if there is a way to apply the styles that are already defined in a stylesheet, without having to re-defining them in a css() function.

like image 316
Maximus S Avatar asked Dec 23 '13 07:12

Maximus S


1 Answers

You need to escape name of class here.

Change

$('.some_div').append("<li class="hi">hey!</li>");

to

$('.some_div').append("<li class='hi'>hey!</li>");

OR

$('.some_div').append("<li class=\"hi\">hey!</li>");

DEMO here.

Demo with style:

$('.some_div').append("<li style='color:green;'>hey!</li>");

OR

$('.some_div').append("<li>hey!</li>").find("li:last").css("color","yellow");

Demo here.

like image 148
codingrose Avatar answered Sep 23 '22 22:09

codingrose