Main content
Course: Computer programming - JavaScript and the web > Unit 6
Lesson 4: DOM modification- Changing attributes
- Challenge: Avatar attributes
- Changing styles
- Challenge: Style guide
- Changing CSS classes
- Challenge: Classification
- Setting innerHTML and textContent
- Challenge: The inside story
- Creating elements from scratch
- Challenge: Create a solar system
- Summary: DOM modification techniques
© 2024 Khan AcademyTerms of usePrivacy PolicyCookie Notice
Summary: DOM modification techniques
Modifying an existing element
We covered various ways that you can modify aspects of an existing element:
Modifying attributes
You can set an attribute on an element by setting the property of the same name. For example, to change the
src
of an <img>
:imgEl.src = "http://www.dogs.com/dog.gif";
In addition, you can also use the
setAttribute
method, like so:imgEl.setAttribute("src", "http://www.dogs.com/dog.gif");
If you want to remove an attribute, you should do that with
removeAttribute
- like to remove the disabled
attribute off a button, effectively enabling it:imgEl.removeAttribute("disabled");
Modifying styles
You can change styles just like how you change attributes, by accessing the
style
property of the element, and setting the corresponding property. For example, to change the color:headingEl.style.color = "hotpink";
Remember to "camelCase" the multi-word CSS property names, since hyphens are not valid JS property names:
headingEl.style.backgroundColor = "salmon";
Modifying class names
To add a class to an element, you can set the
className
property:mainEl.className = "warning";
That will override any existing classes, so you should do this instead if you just want to add to the list of classes:
mainEl.className += " warning";
In newer browsers, you can use the
classList
functionality instead:mainEl.classList.add("warning");
Modifying inner HTML / text
To completely replace the contents of an element with an arbitrary string of HTML, use
innerHTML
:mainEl.innerHTML = "cats are the <strong>cutest</strong>";
If you don't need to pass in HTML tags, you should use
textContent
instead:mainEl.textContent = "cats are the cutest";
Generally, you should be careful when using either of these 2 properties, because they will also remove event listeners (which we teach in the next tutorial).
Creating elements from scratch
There is a whole set of functions that you can use to create entirely new elements and add them to the page.
To create a new element, use the aptly named
createElement
:var imgEl = document.createElement("img");
To append it to the page, call
appendChild
on the target parent element:document.body.appendChild(imgEl);
Want to join the conversation?
- why does JavaScript in html not seem to care about semicolons? it works fine whether i put a semicolon at the end of a line or not.(101 votes)
- It's a feature called "Automatic Semicolon Insertion" (or ASI). Javascript interpreters will add semi-colons for you.(124 votes)
- is there a difference in between using
window.document
ordocument
? both work, same foralert
andwindow.alert
(15 votes)- Absolutely nothing.
window
is the default object when using Javascript to manipulate HTML, meaning, if you don't specify another object, that's what JS will assume you're meaning.(24 votes)
- In the solar system challenge I made this code:
var divEl = document.createElement("div");
divEl.className = "planet";
divEl.style.backgroundColor = "orange";
document.body.appendChild(divEl);
var divEl1 = document.createElement("div");
divEl1.className = "moon";
divEl1.style.backgroundColor = "white";
document.body.appendChild(divEl1);
and Warning is this:
"Hm, are you appending the new div to the planet div you created in step 1? The moon div should be a child of the planet div in the DOM."
I dont get what exactly have to do. To make child under the child or...? Moon appear but warning is there too! Can someone help me, please!(11 votes)- you can try to append the child by using "divEl" instead of "document.body"(10 votes)
- I'm confused about the content/structure of the DOM tree. If I want to add an element to it, I have to know where I am going to add it but I have no idea what the DOM tree looks like and how to reference a specific node. Is there a way to view or print it out so I can see what nodes exist?(5 votes)
- The DOM has the body as the trunk of the tree, with all visual elements stemming from it. Those elements are like the branches. Elements inside of those are like smaller branches or leaves.
For example: The body is the trunk. Aul
is a branch. And eachli
inside theul
is a leaf. Eachli
is a child of theul
and theul
is a child of the body.(10 votes)
- When I need to rename things with dashes in CSS, when do I need to use camel code versus when is it ok to leave the dashes in?(6 votes)
- CSS properties are always defined with hyphens between words. Because you cannot have a hyphen in a JavaScript property name, you must use camelCase to access the corresponding
style
property in JavaScript.
These CSS properties:#element {
background-color: #f00;
font-size: 20px;
}
Correspond to these JavaScript style properties:var element = document.getElementById("element");
console.log(element.style.backgroundColor);
console.log(element.style.fontSize);(11 votes)
- In the solar system challenge where it says to add a background to the div, should it be added in JS part? When adding to the CSS part, it works fine but keeps saying "Make sure you set the background color of the div so that the planet actually shows up.", and when I try to add it in the JS part ( like,
var divEl = document.createElement("div");
divEl.className = ("planet");
divEl.style.backgroundColor = "green"; ) it does not work.
Thank you.(0 votes)divEl.className=("planet")
is wrong - Remove the brackets surrounding "planet".
Also did you use appendChild anywhere in your code? If not then your div will not be visible.
Just some advice - Best thing to do if you're having trouble with the exercises is to open up another window from prior lessons that we learnt from and use it as a reference. Then do it a second time without help so you know you actually learnt it. Just keep repeating the exercises until you can do them without help.(22 votes)
- I'm still ultimately confused why for non interactive elements we are even using DOM for this. Shouldn't we stick to using HTML and the appropriate CSS? It's cleaner and shouldn't it run faster than having to also run the javascript unless it's something interactive where we have to use DOM?(4 votes)
- The reason you are learning to edit HTML with JavaScript is because you won't use it for silly purposes. This is just a simple way to teach it since you already know HTML. An example of using JavaScript would be to create a clock.
The clock isn't interactive; I can't click it and have something special happen, it just has moving hands that match your computer's time. There isn't a hard rule that describes every case in which you'd need JavaScript. You will simply know when and how to use it.
So yes, you could have just done it in HTML and CSS, but you might want to make something interactive or something that requires math. You can even make games with JavaScript!
Good luck and happy coding!(7 votes)
- In the Solar System challenge, what is actually going on when you create a div element? After completing the challenge (with a lot of help from reading comments and questions below) I played around with the code. The original code is this:
var planetEl = document.createElement("div");
planetEl.className="planet";
planetEl.style.backgroundColor="blue";
document.body.appendChild(planetEl);
var moonEl = document.createElement("div");
moonEl.className="moon";
planetEl.appendChild(moonEl);
So I changed some things for fun and got odd results. For example, I changed ("div") to ("body") and noticed the items changed size. I then changed it to ("span") and with the position at "relative" it became an ellipse. I sometimes find that by playing around lke this I get a more intuitive sense of what I am doing.
Not this time.
My point is, I don't actually understand the background logic that is going on here. I feel like the last few lessons have been a lot of "here is what you do" with no explanation of the underlying logic.(6 votes) - Hello guys, I have a problem with the last challenge. Here is my code:
<script>
var divEl = document.createElement = "div";
divEl.className = "planet";
divEl.style.backgroundColor = "black";
document.body.appendChild(divEl);
</script>
When I try to run it, it says that JavaScript has encountered a run-time error, and in the console is says "undefined is not an object". Can someone please explain what is the problem?(2 votes)- I think the first line should be
var divEl = document.createElement("div");
(6 votes)
- What's the difference between using...
var imgEl = document.createElement("img");
and
var imgEl = document.body.createElement("img");?(2 votes)- The second one doesn't work.
document.body.createElement
doesn't exist.(4 votes)