user2948897
user2948897

Reputation: 169

Javascript with CSS

How do I use document.write with my stylesheet? For example, I want to use div, table and caption in a sepearte stylesheet and reference it in the document.write function in my HTML file.

Please consider the following stylesheet:

.div {
width:auto;
margin;10px;

}

.table {
background-color:purple;
border:1px solid
border-spacing:1px
border-collapse:separate;
padding:35px;

}

.caption {
background-color:purple;


}

Then I want to use these classes in the document.write() function in my HTML document:

<head> <link rel="stylehseet" href="style/myStyle.css"></head>
<body>
<script Language="JavaScript">
document.write('<div style="width:auto; margin:10px;">\
            <table style="border="1" cellspacing="1" cellpadding="35">\
            <caption style="background-color:purple;"> Table </caption>')
</script>
</body>

Instead of having the style defintions in the HTML file, how can I put the defintions in the CSS file and reference it in the HTML?

How do I combine forces, so to speak?

Upvotes: 1

Views: 119

Answers (2)

Emilio Gort
Emilio Gort

Reputation: 3470

.div {
  width:auto; 
  margin:10px;
}
.table,td  {
    border-collapse:collapse;
    border: 1px solid #000;/*# is the black color*/
    border-spacing: 10px;/*cellspacing*/
    border-collapse: separate;/*cellspacing*/
    padding: 35px;cellpadding
}
.caption {
  background-color:purple; /*caption doesn't support background property*/
}

in the head put your link to the css file

<link rel="stylesheet" type="text/css" href="style/mystyle.css">

the javascript part

<script Language="JavaScript">
 document.write('<div class="div">\
        <table class="table"><tr><td></td></tr></table>\
        <caption class="caption"> Table </caption></div>')
</script>

http://jsfiddle.net/emigort/pJbKu/

Upvotes: 1

jeremyjjbrown
jeremyjjbrown

Reputation: 8009

div 
 {
    width:auto; 
    margin:10px;
 }

just move your styles into the sheet. The . BTW will target a class, you are targeting tags in your javascript. Then link the css file into your page

<head>
    <link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

if you must do it in javascript

var css = 'div { width:auto; margin:10px; }',
    head = document.head || document.getElementsByTagName('head')[0],
    style = document.createElement('style');

style.type = 'text/css';
if (style.styleSheet){
  style.styleSheet.cssText = css;
} else {
  style.appendChild(document.createTextNode(css));
}

head.appendChild(style);

Upvotes: 1

Related Questions