Reputation: 2829
I'm trying to add a inline-style using JavaScript as soon as the site is loaded (can't use CSS directly due to reasons). I want all text within a table to be horizontally centered,
This is my JavaScript code so far:
window.onload = center_content();
function center_content (){
var all_td = document.getElementsByTagName('table');
all_td[0].style.textAlign = "center !important";
}
Edit: Code corrected so far
jsfiddle: http://jsfiddle.net/GinSan/h46mz6na/4/ (remember that I can't directly use CSS in this case)
Any help is much appreciated. No jQuery solutions please.
Upvotes: 1
Views: 3995
Reputation: 99504
Hyphen-separated properties of style object should be used in camelCase when it comes to JavaScript.
Try using so:
document.getElementsByTagName('table')[0].style.textAlign = "center";
You could also use .style["text-align"]
to achieve the same result.
However if you want to set the priority (i.e. !important
keyword), not only the value, you could use .setProperty()
method as follows:
document.getElementsByTagName('table')[0].style.setProperty("text-align", "center", "important");
And one more thing, by using ()
at window.onload = center_content();
you're executing center_content()
immediately and assigning the returned value which is undefined
to window.onload
.
You could either do it like window.onload = center_content;
or use an anonymous function:
window.onload = function () { /* ... */ };
Upvotes: 4
Reputation: 883
You cannot use -
in a variable name or property. Instead use style.textAlign
Upvotes: 0