Reputation: 4332
I am creating a table using JavaScript, and I have by default all cells in the table to be right aligned:
.my-table td { text-align: right; }
However, in certain cases, I want the cells to be left aligned.
.my-table td.left { text-align: left !important; }
For those cells, I have added the class name like so:
my_cell.classList.add("left");
When in look in the DOM tree, I can see that the name has been successfully applied to the cells. However, the styling isn't applied and when I look at the element's styles in the developer tools, it doesn't even appear. Usually if a style gets overwritten, I'll see the class name appear under styles and there's a line through the style that got overwritten. However, the "left" class name doesn't appear under possible applied styles at all, even though it is in the element's class name list <td class="left">
when I look at the DOM tree.
Why/how can the class name be getting applied to the element but there be absolutely no style associated with it?
I've tried permuting my definitions:
.my-table td.left { text-align: left !important; }
.my-table td .left { text-align: left !important; }
etc., but nothing works.
Here is my current script:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#reference").load(URL);
let table_div = document.createElement("table");
table_div.classList.add("my-table");
let tbody = table_div.appendChild(document.createElement("tbody"));
let rows = document.getElementById("reference").getElementsByTagName("tr");
for (let i = 0; i < rows.length; i++) {
let table_row = tbody.appendChild(document.createElement("tr"));
if (i === 0) { // leave header row alone
table_row.innerHTML = rows[i].innerHTML;
continue;
}
let cells = rows[i].getElementsByTagName("td")
for (let j=0; j < cells.length; j++) {
let td = table_row.appendChild(document.createElement("td"));
let val = cells[j].innerHTML;
td.innerHTML = val;
if (val.includes("%"))
continue;
td.classList.add("left");
}
}
document.getElementById("my_table").appendChild(table_div);
});
</script>
Upvotes: 1
Views: 1624
Reputation: 31
i don't know why that is happening but you could try creating two classnames with the same properties except the alignment and then toggle (meaning remove or insert) when needed.
You could try the built in .toggle() method. Just a suggestion ☺
Upvotes: 1