简体   繁体   中英

how to apply css to dynamic HTML content?

I new to CSS and learning.

My question is,

if at all my HTML content is loaded with with a delay may be because of an ajax request, And if I append that html response to the already loaded div tag;

How will I apply CSS to the inner HTML.

let say I have and div tag,

<div class="row">
    <div class="col-md-5 col-md-offset-2">
        <div id="theTableContainer"></div>
    </div>
</div>

If I am trying to load an html in the div having id "theTableContainer",

I will apply css in the callback function of xhr success after the html is appended to div

as follows

$("#theTableContainer table tr:gt(0)").each(function(){
        $(this).find("td:eq(2)").
            css("background-color","#8600e6").
            css("color","#F8F8FF").
            css("font-weight","bold");
});

Is there a better way ?

Please find the link below for the working code.

My Working example

The better way is to add css classes which you want to add and then use addClass to add css dynamically.

 $("#theTableContainer table tr").each(function(){ $(this).find("td").addClass('background color font-weight'); }); 
 .background { background-color: red; } .color { color: white; } .font-weight { font-weight: 'bold'; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="row"> <div class="col-md-5 col-md-offset-2"> <div id="theTableContainer"> <table> <tr> <td> example </td> </tr> </table> </div> </div> </div> 

You may always add the style in your css:

#theTableContainer table tbody tr td:nth-child(3){
  background-color: #8600e6;
  color: #F8F8FF;
  font-weight: bold;
}

The updated fiddle .

An alternative way is based on grouping the css :

$(this).find("td:eq(2)").css({"background-color": "#8600e6", 
                              "color":"#F8F8FF",
                              "font-weight":"bold"});

You could make a class with all the CSS properties you want:

.active {
    background-color: #8600e6;
    color: #F8F8FF;
    font-weight: bold;
}

And apply it:

$(this).find("td:eq(2)").addClass('active');

Here is jfiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM