Java Reference
In-Depth Information
manipulating the dom
DOM scripting is the manipulation of an HTML page after it's loaded into the browser. Up to this
point, you've examined the properties and methods of the basic DOM objects and learned how to
traverse the DOM through JavaScript.
Throughout the previous section, you saw some examples of manipulating the DOM; more
specifically, you saw that you can change the color and font family of text contained within an
element. In this section, you expand on that knowledge.
accessing elements
As you saw in the previous section, the DOM holds the tools you need to find and access HTML
elements; you used the getElementById() method quite frequently, and through examples you saw
how easy it was to find specific elements in the page.
When scripting the DOM, chances are you have a pretty good idea of what elements you
want to manipulate. The easiest ways to find those elements are with the getElementById() ,
querySelector() , and querySelectorAll() methods. If an element has an id attribute, use
getElementById() because it is the fastest way to find an element in the page. Otherwise, you'll
need to use the querySelector() and querySelectorAll() methods.
Changing appearances
Probably the most common DOM manipulation is to change the way an element looks. Such a
change can create an interactive experience for visitors to your website and can even be used to alert
them to important information or that an action is required by them. Changing the way an element
looks consists almost exclusively of changing CSS properties for an HTML element. You can do this
two ways through JavaScript:
Change each CSS property with the style property.
Change the value of the element's class attribute.
Using the style property
To change specific CSS properties, you must look to the style property. All browsers implement this
object, which maps directly to the element's style attribute. This object contains CSS properties,
and by using it you can change any CSS property that the browser supports. You've already seen the
style property in use, but here's a quick refresher:
element.style.cssProperty = value;
The CSS property names generally match those used in a CSS style sheet; therefore, changing the
text color of an element requires the use of the color property, like this:
var divAdvert = document.getElementById("divAdvert");
divAdvert.style.color = "blue";
 
Search WWH ::




Custom Search