19 DOM Manipulation
In the previous chapter, you learned a basic two step method for manipulating the DOM:
- Retrieve the element or elements you want to change
- Change the elements you retrieved
So far the change step is restricted to changing the content of an element. In this section, we’ll look at changing styles, classes, and other attributes.
The Style Attribute
Do it Yourself
Load helloworld.html from the Full Stack Example Pack into a browser. Open the developer console but instead of the Console tab, go to the Elements tab. This is a representation of the browser’s DOM.
Now right click the img element, select “add attribute“, and give this image a style attribute (e.g., style=”width:100px”). You should see the change reflected on the page immediately.
We have not yet officially introduced the HTML style attribute, but it can be used to add CSS property values to a single element. You can add multiple property values in a style element as long as they are separated with semicolons. In the CSS cascade, properties from the style attribute are added last, so you can use it to override any rules that might apply to the element.
Here’s an example:
<h1 style="border: 3px solid black; background-color: royalblue">Am I blue?</h1>
Changing an element’s CSS information can be done most easily by accessing the style field of the corresponding DOM element. The style field contains an object with fields for all possible CSS properties.
Do it Yourself
Load innerHTMLExample1.html from the Full Stack Example Pack, open the browser console, and type the following:
let e = document.getElementById("heading"); e.style.color = "red";
Now try changing other CSS styles in the same way. Add a border, change the font, position the header below the paragraph, etc.
Now go to the Elements view and look at the h1 element. You will see that it now has a style attribute with all the information you added through JavaScript. Note that the page source does not contain this information.
In addition to assigning or changing style information, you can also read style information from the fields of the style object, but you cannot read any CSS properties that were applied as part of a stylesheet in this way. Only properties specified in the HTML style attribute or assigned through the style field in a JavaScript program will have values.
Do it Yourself
Load innerHTMLExample2.html from the Full Stack Example Pack. Note that the div element is red with a border.
Now hit go to the JavaScript console and type the following:
let e = document.getElementById("target"); e.style.color; e.style.border;
Why does one of the above lines give you a value but not the other? View the original page source to see if you can figure it out.
The only wrinkle in accessing the style object is that you can get into problems with the dot notation for hyphenated style properties like background-color. The problem is that the JavaScript expression e.style.background-color looks to the JavaScript interpreter like we are subtracting the variable color from the field e.style.background.
There are two workarounds for this.
- Use associative array notation and reference e.style[“background-color”] instead.
- Use dot notation but convert the hyphenated-property-name to a camelCasePropertyName (in CamelCase you capitalize the first letter of each word, often leaving the first letter as lowercase). For example background-color can be accessed through dot notation as backgroundColor, border-radius-top-left becomes borderRadiusTopLeft, and so on.
Do it Yourself
Load innerHTMLExample1.html from the Full Stack Example Pack. Open the console and type the following:
lete = document.getElementById("heading"); e.style.backgroundColor = "red"; e.style["background-color"] = "blue";
Now change some other hyphenated properties, like font-size, border-radius, etc.
Connections
Many JavaScript programmers prefer to use associative array notation for the style object. It means that you can use the original CSS style property names in your code instead of having to convert them. But this is a matter of personal preference and either choice is good as long as you stay consistent with yourself.
HTML Classes
Sometimes you may want to change a large number of CSS property values at once. In this case, a good option might be to define style rules for two different classes, and then change the className field of the element. This will automatically update the style of the element to match its new class, effectively changing many styles at once.
Do it Yourself
Load classNameChangeExample.html from the Full Stack Example Pack. Open the console and type the following:
document.getElementById("maindiv").className="classtwo"
You should see a big change. Take a look at the source code for this file to see how this change happened. Can you use a single command to change it back to the way it was originally?
Often an element will be a member of multiple classes. In that case, it’s better to use the classList field than className. The classList field is an object that contains all the classes of which this element is a member. It has add and remove methods for modifying class membership.
Do it Yourself
Load classNameChangeExample.html from the Full Stack Example Pack. Open the console and type the following:
let e = document.getElementById("maindiv"); e.classList.add("classtwo");
You should see a big change again, but it will look different from the last DIY box. This is because the element is now a member of both classone and classtwo. Take a look at the element in the Elements tab to see both class names.
You can also examine the class list with this command in the console:
e.classList
Or this one:
e.className
To finish the job of changing from classone to classtwo through the classList field, you have to remove classone:
e.classList.remove("classone");
Attributes
You can also access, change or add any other attribute of an element by accessing the field for that attribute. For example, if you want to change an image, you can modify its src attribute by accessing the src field of the corresponding DOM element. Or if you want to change a link, you can modify the href attribute of the DOM element.
Do it Yourself
Open the chrome console for this page and execute the following command to retrieve the node corresponding to this DIY box:
let node = document.getElementById("testDIY");
Now add a title
attribute:
node.title="Read Me!";
Now hover the mouse over this DIY box to see the effect of this statement. Then right-click and choose Inspect Element to see the attribute you added to the DOM.
This link goes to Google. It has an id
of “testLink”. Can you enter commands in the browser console to redirect the link to example.com instead?
<exercises chapter=”moreDOM”>
- Create a web page with a single “hello world” paragraph. Create a function on the page that prompts the user for a color, and then sets the color of the “hello world” element according to what they typed.
- Modify the script from the last exercise so that the user can specify both the style property to change and the value (note that you will have to use associative array notation to access the style property the user chooses).
- Go back to the addition.html exercise from the previous chapter (or get it fresh from the Full Stack Example Pack). Change the file so that the result field changes to green if the user gets your question right, otherwise it should be red.
- Modify addition.html again so that if the user fails to enter a valid number, the h1 element turns into a solid red box with a thick black border around it. You should accomplish this by defining a class and adding it to the h1 element. If the function is run again and the user enters a valid number, the class should be removed from the h1 element.
- Get the moveme.html file from the Full Stack Example Pack. When you run it you will see a circle (actually a div element) inside a box (another div element). Both of these elements have their CSS position property set to absolute. This allows you to set a CSS top and left property to position the image on the page. If you are not familiar with how absolute positioning works, you can read about it in the comments of the moveme.html file or in the W3Schools CSS Positioning page.
- Your first task is to write a function that will use a confirm dialog to ask the user if they want to move the box. If they click OK, move the circle to a random position within the box. if they click CANCEL, do nothing. You should be able to call the function repeatedly from the console to move the circle around.
- Your second task is to write a second function that uses a prompt dialog to ask the user to enter U, D, L, R, or Q (for up, down, left, right and quit) and then move the circle 20 pixels in the desired direction. Use a variable or variables to track the current position of the circle. You should be able to call the function repeatedly from the console to move the circle around.
- Modify your function from part b so that the user cannot move the circle out of bounds.
- Write a JavaScript program in a .js file and load it into a web page using a script element. The web page should have a div element in the body of the page with its CSS displayproperty set to none (this will hide it). The script file should define a function with two parameters (message and type). It should do the following: Retrieve the div element, change its innerHTML so that it contains the message, then change the style according to the type parameter (1 = black text, yellow background, with the word “Warning: ” before the message; 2 = white text, red background, the word “Error:” before the message; otherwise gray text, green background. Then change the CSS display property to block to make the message pop up. Load the page into chrome and test your function in the Console.Extra Challenge: use setTimeout to make the message disappear again automatically after 5 seconds.
- Go back to the addition.html file from the previous sections and create CSS rules for two classes named correct and incorrect. The correct class should make an element big, centered in the middle of the screen, with a border and a happy background color. The incorrect class should make an element small, positioned in the lower right, with sad colors. Then modify the function to change the class of the result element appropriately depending on whether the user gets your question right or wrong.
- Get the file mood.html from the Full Stack Example Pack and follow the instructions in the comments at the top. Here are the image files you will need (right click and save them to an appropriate folder), or get them from the images folder of the Full Stack Example Pack.