DOM methods: write(), writeln(), getElementById(), getElementsByName()

DOM methods reach into the page: getElementById returns the single element with that id (or null), getElementsByName returns a collection you must loop over, and the old document.write / writeln dump text into the page but will erase everything if called after the page has loaded.

9 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Grabbing the right element

To update FestConnect's seat counter you need to find that one <p> in the DOM tree. To read which year a student picked, you need all the radios named year and check which is selected.

Those are two different jobs: fetch one element by its unique id, or fetch a group of elements by a shared name. The DOM gives a method for each, plus an old pair of methods (write, writeln) that are handy to know and easy to misuse.

Theory

Roll number versus class name

Finding a student by roll number gives you exactly one person: ids are unique, like getElementById. Calling out a class name ('all second years, stand up') gives you a group: that is getElementsByName, which returns a collection you then go through one by one. One is a single result; the other is a list you must iterate.

Theory

The methods

  • `document.getElementById("seats")`: returns the one element with that id, or null if none exists.
  • `document.getElementsByName("year")`: returns a collection of all elements with that name (a radio group), which you index ([0]) or loop over.
  • `document.write(text)` / `writeln(text)`: write text straight into the page. writeln adds a newline. Safe during initial load only.

Modern relatives: getElementsByClassName, and querySelector (first match by CSS selector).

Practical

Update one, read a group

<p id="seats">Seats left: 30</p>
<input type="radio" name="year" value="1">
<input type="radio" name="year" value="2" checked>

<script>
  // ONE element by id
  let seats = document.getElementById("seats");
  seats.textContent = "Seats left: 29";

  // a GROUP by name: loop to find the checked one
  let years = document.getElementsByName("year");
  let chosen = "";
  for (let i = 0; i < years.length; i++) {
    if (years[i].checked) chosen = years[i].value;
  }
  console.log("Year chosen: " + chosen);   // "2"

  // document.write is fine here (during load), but calling it
  // after load would ERASE the whole page:
  // document.write("hi");   // avoid after load
</script>

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Think first

One node or a list?

getElementById("seats") lets you write .textContent straight away, but getElementsByName("year")[0].value needs the [0]. Why the difference, and what happens if you forget the index on the group?

Show the answer

getElementById returns a single element, so you use its properties directly. getElementsByName returns a collection (a NodeList) of possibly many elements, so you must pick one with an index ([0]) or loop. Forget the index and you try to read .value on the whole collection, which is undefined, because a list has no .value; only its items do. Single vs group decides whether you index.

Quiz

A student adds `document.write("Thanks for registering")` inside a button's click handler. On click, the entire FestConnect page vanishes and shows only that text. Why?

  1. document.write after the page has loaded overwrites the whole document
  2. getElementById is required before any document.write
  3. The button needed getElementsByName instead
  4. document.write can only print numbers, not text
Show the answer

document.write after the page has loaded overwrites the whole document

document.write writes into the document stream; once the page has finished loading, calling it reopens and overwrites the entire document, wiping everything to show only the new text (A). It is unrelated to getElementById (B) or getElementsByName (C), and it prints text fine (D). The lesson: never use document.write after load. To update part of the page, grab an element by id and set its textContent instead.

Watch out

DOM method traps

1. document.write after load wipes the page. Use it only in initial load demos; for updates, target an element and set textContent/innerHTML.

2. getElementById returns null if the id is wrong or the script ran too early: then .textContent throws. Check the id and script placement (Unit 3).

3. Treating a collection as one element: getElementsByName (and getElementsByClassName) return lists; index or loop them, do not call .value on the list itself.

Theory

Everything is in place for interactivity

You can now find any element (methods), read and change it (properties), and react to the user (events, Unit 3). Unit 5 ties them together: a register() function triggered on submit that reads the form with these methods, validates it, updates the seat counter, and either redirects or shows an error. FestConnect is about to come alive.

Summary

Key takeaways

  • getElementById(id) returns the single element with that id, or null.
  • getElementsByName(name) returns a collection (like a radio group); index [i] or loop over it.
  • document.write / writeln dump text into the page; calling them after load overwrites the whole document.
  • To update part of a loaded page, grab an element by id and set textContent/innerHTML, not document.write.
  • Modern relatives: getElementsByClassName, querySelector (first CSS match).
  • Memory hook: id is a roll number (one), name is a class call (a group).

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from JavaScript Objects

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

DOM methods: write(), writeln(), getElementById(), getElementsByName() · Web Designing-1 (option A) · Gri-Learn