0
votes

HTML

<div class="wrapper">
    <div class="profile">
        <div id='entrydata'></div>
    </div>
</div>

Javascript

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(function() {
    var dmJSON = "data.json";
    $.getJSON(dmJSON, function(data) {
        $.each(data.records, function(i, f) {
            var $table = "<table border=5><tbody><tr>" + "<td>" + f.Clue + "</td></tr>" + "<tr><td>" + f.Answer + "</td></tr>" + "<tr><td>" + f.Status + "</td></tr>" + "<tr><td> " + f.Views + "</td></tr>" + "</tbody>&nbsp;&nbsp;&nbsp;</table>"
            $("#entrydata").append($table)
        });
    });
});
</script>

The above code creates tables dynamically and displays data from my JSON file. I would like to apply CSS(Table border color, table bg color, font size, font-family etc.) to these tables. Any solution to this would be helpful. Thanks in advance.

3
Add class to the table and then put styles into your CSS.pavel
You need to have classes or IDs or inline css to elements which are to be appended in DOM..Syle will get affected as the elements are been rendered...Rayon

3 Answers

2
votes

Simple. Add one class for your table and apply the styles through css.

var $table="<table class='mystyles' border=5><tbody><tr>" + "<td>" + f.Clue + "</td></tr>" + "<tr><td>" + f.Answer + "</td></tr>" + "<tr><td>" + f.Status + "</td></tr>" + "<tr><td> " + f.Views + "</td></tr>" + "</tbody>&nbsp;&nbsp;&nbsp;</table>"

CSS

 table.mystyles
 {
     //your styles
 }
 table.mystyles td
 {
     //your styles
 }
1
votes

You can add style or class to the table while creating.

var $table = "<table border=5 style='border: 1px solid red, ...'><tbody><tr>" + "<td>" + f.Clue + "</td></tr>" + "<tr><td>" + f.Answer + "</td></tr>" + "<tr><td>" + f.Status + "</td></tr>" + "<tr><td> " + f.Views + "</td></tr>" + "</tbody>&nbsp;&nbsp;&nbsp;</table>"

By class:

var $table = "<table border=5 class='myTable'><tbody><tr>" + "<td>" + f.Clue + "</td></tr>" + "<tr><td>" + f.Answer + "</td></tr>" + "<tr><td>" + f.Status + "</td></tr>" + "<tr><td> " + f.Views + "</td></tr>" + "</tbody>&nbsp;&nbsp;&nbsp;</table>"

CSS:

.myTable {
    border: 1px solid red;
    ....
}

Or

After table is created and appended to entrydata.

$('#entrydata table').css({
    border: '1px solid red',
    ....
});

I would recommend to use class approach.

0
votes

Cant you apply your style on this part of code:

var $table="<table border=5 style='background:#fff;.....'><tbody><tr>" + "<td>" + f.Clue + "</td></tr>" + "<tr><td>" + f.Answer + "</td></tr>" + "<tr><td>" + f.Status + "</td></tr>" + "<tr><td> " + f.Views + "</td></tr>" + "</tbody>&nbsp;&nbsp;&nbsp;</table>"