Applying styles from CSS to newly appended elements

后端 未结 3 686
太阳男子
太阳男子 2021-01-04 19:13

I add an element to a parent div dynamically.

$(\'.some_div\').append(\"
  • hey!
  • \")

    In my CSS,

    
    
            
    相关标签:
    3条回答
    • 2021-01-04 19:49

      Try this

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

      If you want to apply specific css for this element

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

      If you want to apply CSS based on class

      $('.hi').css("color","white");
      
      0 讨论(0)
    • 2021-01-04 19:54

      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.

      0 讨论(0)
    • 2021-01-04 20:05

      Your string concatenation could be the problem, since your string literal is enclosed within "" any occurrence of " within the string has to be escaped

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

      Demo: Fiddle

      Note: also note that li is a valid child for ul or ol elements, so the some_div must be either one of them

      0 讨论(0)
    提交回复
    热议问题