Java Reference
In-Depth Information
Here is an advertisement.
</div>
<script>
var divAdvert = document.getElementById("divAdvert");
divAdvert.className = "new-style";
</script>
</body>
</html>
Save this as ch9 _ example5.html .
Two key differences exist between ch9 _ example4.html and ch9 _ example5.html . The first is the
addition of a CSS class called new‐style :
.newStyle {
font-style: italic;
text-decoration: underline;
}
This class contains style declarations to specify italicized and underlined text.
The second change is in the JavaScript itself:
var divAdvert = document.getElementById("divAdvert");
divAdvert.className = "new-style";
}
The first statement retrieves the <div/> element by using the getElementById() method. The second
statement changes the className property to the value new‐style . With this line, the divAdvert
element takes on a new style rule and the browser changes the way it looks.
Note Although it wasn't demonstrated here, the HTML class attribute, and
thus the className property, can contain multiple CSS class names. You see
more about multiple class names in Chapter 16.
positioning and moving Content
Changing the appearance of an element is an important pattern in DOM scripting, and it finds its
place in many scripts. However, there is more to DOM scripting than just changing the way content
appears on the page; you can also change the position of an element with JavaScript.
Moving content with JavaScript is just as easy as using the style object. You use the position
property to change the type of position desired, and by using the left and top properties, you can
position the element:
var divAdvert = document.getElementById("divAdvert");
divAdvert.style.position = "absolute";
 
Search WWH ::




Custom Search