Finding and changing nodes
querySelector, textContent, classList, dataset, and the handful of methods that cover almost everything you will ever do without a framework.
The query methods: querySelector returns the first match, querySelectorAll returns all of them as a static NodeList. Both take any CSS selector, which means everything you learned in lesson three transfers directly. getElementById is marginally faster and almost never enough faster to matter.
One distinction useful to know early: querySelectorAll returns a static list, a snapshot. getElementsByClassName and getElementsByTagName return live collections that update as the DOM changes. Iterating a live collection while removing items from it is a classic bug where you process every other element and cannot see why.
Changing content: textContent sets text and treats everything as text. innerHTML parses the string as HTML. That difference is a security boundary, not a convenience. Any user-supplied string going into innerHTML is a cross-site scripting hole, and the fact that <script> tags inserted that way do not execute is not protection, <img src=x onerror=...> does.
The safe pattern for building content is createElement, then set properties, then append. It is slightly more code and it is unconditionally safe. Where you really need to insert markup, insertAdjacentHTML with a sanitised string, or the Sanitizer API where available. Use textContent unless you have a specific reason, and when you do have one, write the reason in a comment.
The rest of the working vocabulary is small. classList.add/remove/toggle/contains for classes, never string-concatenate className. dataset.thing for data-thing. setAttribute/getAttribute for attributes with no property. append, prepend, before, after, remove for placement, all of which take multiple arguments and accept strings as text. closest() to walk up looking for an ancestor matching a selector, which is the method that makes event delegation ergonomic in the next chapter.
Now build a to-do list with no framework and no libraries. Add items, remove them, mark them done, and persist to localStorage. Three constraints: use textContent for anything a user typed; build every element with createElement; and make it fully keyboard operable. Then, and this is the part that matters, deliberately try to break your own version by entering <img src=x onerror="alert(1)"> as a to-do. If an alert appears, you used innerHTML somewhere. Find it.
Build this in your own editor
This one runs on your machine rather than in the browser workbench. Work to the outcomes below, then come back and mark it complete.
You should now be able to
- Query and modify the DOM without a library
- Choose between textContent and innerHTML correctly, and know the security reason
- Build and insert elements safely
- Know which methods return a live collection and why that matters
Loading…