Skip to content Skip to sidebar Skip to footer

How To Apply Style Sheets To Dynamically Created Elements?

this should be an easy one: I have the following code: Insert title here<

Solution 1:

It is not dynamically created issue. It is because you haven't set the class to table. As Bootstrap Docs says:

You have to use <thead> and <tbody> for the class to work.

To add in your answer:

var thead = document.createElement("thead");
thead.appendChild(headRow);
var tbody = document.createElement("tbody");
tbody.appendChild(dataRow);

Add this for a quick fix:

$("tr:first-child").wrap("<thead/>");

Your final code should look like:

var table = document.createElement("table");
    table.setAttribute("id","table");
    var headRow = document.createElement("tr");
    var dataRow = document.createElement("tr");
    var head = document.createElement("th");
    var data = document.createElement("td");
    var thead = document.createElement("thead");
    thead.appendChild(headRow);
    var tbody = document.createElement("tbody");
    tbody.appendChild(dataRow);
    head.innerHTML="head";
    data.innerHTML="data";
    headRow.appendChild(head);
    dataRow.appendChild(data);
    table.appendChild(thead);
    table.appendChild(tbody);
    console.log(document.styleSheets);
    table.className = "table";
    document.getElementById("test").appendChild(table);

Solution 2:

The slight difference in styling is because Bootstrap relies on the <tbody> and <thead> elements to apply styling. If you're dynamically creating elements, you need to create these too:

var thead = document.createElement("thead");
thead.appendChild(headRow);
var tbody = document.createElement("tbody");
tbody.appendChild(dataRow);

Then, instead of appending headRow and dataRow directly, append the newly created elements:

table.appendChild(thead);
table.appendChild(tbody);

Example Fiddle

Solution 3:

    $(function () {
        var table = $('<table></table>').attr('id', 'table').addClass('table')
        var head = $('<th></th>').html('head')
        var data = $('<th></th>').html('data')
        var headRow = $('<tr></tr>').append(head)
        var dataRow = $('<tr></tr>').append(data)
        table.append(headRow)
        table.append(dataRow)
        console.log(document.styleSheets);
        $('#test').append(table);
    })

Solution 4:

Best way to add style sheet to dynamically added content is to use classList

Please refer below link: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

OR

You can use element.style.cssProperty

Post a Comment for "How To Apply Style Sheets To Dynamically Created Elements?"