Alan Wells
Alan Wells

Reputation: 31310

Dynamically Style/Format a dynamically added column of a table to right aligned using JavaScript

I have a table with a price column that I want right aligned. I could easily do that, but all the rows are added later with:

var row = table.insertRow(-1);

So, there is no existing HTML to add an id to in the original file. There is a <table> tag, but no <tr> or <td> tags.

Here is a jsFiddle with HTML, CSS, and JavaScript:

jsFiddle

enter image description here

I want the price right aligned. How do I dynamically set the alignment of one column with Javascript?

Upvotes: 0

Views: 1756

Answers (1)

David
David

Reputation: 148

You don't need JavaScript at all for that task. You can set the style of your price-column with CSS. Just add the following rule to the CSS:

#myTable tr td:nth-child(3) {
    text-align: right;
}

jsFiddle

If you don't have the option to edit your CSS, you could set the CSS property on your inserted node:

cell3.style.textAlign = "right";

jsFiddle

Of course, the latter would also answer your question to set the style property with JavaScript.

This assumes that you know, that your price column will be the 3rd column.

Upvotes: 1

Related Questions