AI Hints
Home›JavaScript Tutorial›Changing the Page
JavaScript · Lesson 94 of 138

Changing the Page

Text, classes, styles.

⏱ 2 min read▶ Video at 1:53:03🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Once you've found an element, you can change almost anything about it. Its text, its classes, its style, and its attributes, like an image's source or a link's address.

Changing the Page
From the video: Changing the Page
  • Find, then change
  • Text, classes, style
  • Attributes too

Text, classes, and styles

Text content sets the text. Class list dot add puts a class on an element, and the style sheet decides how it looks. Style sets one CSS property directly, written in camel case. And set attribute changes any attribute, like a link's title. The page shows every change.

index.htmlpython
<link rel="stylesheet" href="style.css">
<h1>Status</h1>
<p id="msg">Not started</p>
<p id="note">A small note</p>
<a id="link" href="#">Help</a>
<script>
  const msg = document.querySelector("#msg");
  msg.textContent = "Task complete";
  msg.classList.add("box");

  const note = document.querySelector("#note");
  note.style.fontSize = "30px";
  note.style.color = "crimson";

  document.querySelector("#link").setAttribute("title", "Open help");
</script>
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#f7df1e;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}

Text or HTML

Text content treats what you give it as plain text, so it's always safe. Inner HTML treats it as HTML, so tags become real elements. Never put user input into inner HTML, because someone could inject a harmful script. When in doubt, use text content.

keyvalue
textContentplain text, safe
innerHTMLparses tags, careful!
classListadd, remove, toggle
style.propone CSS property

Summary

Text content, class list, style, and set attribute change elements. Prefer classes for styling, and text content for user input. Next, creating new elements.

Key takeaways
  • textContent
  • classList.add/toggle
  • style, setAttribute
Next up: Creating Elements — adding to the page