OA. free
Free
MathWorks Core Computer Science Core Computer Science Medium

31.

MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.

Append Text Using JS**

Given HTML:

<p id="test" name="hacker">Hello</p>

Which of the following JavaScript code snippets will append " Mr. Bob" after "Hello"?

Pick ONE OR MORE options

Choose one option.
Show answer & explanation
Answer: A. document.getElementById("test").innerHTML += " Mr. Bob";

Option A uses getElementById() which returns a single element directly, so no indexing is needed. Option D uses getElementsByName() which returns a NodeList, so [0] accesses the first matching element. Both correctly append " Mr. Bob" to the innerHTML. Option B fails because getElementsByName() returns a NodeList (not a single element), so .innerHTML is undefined on the collection itself. Option C fails because getElementsById() is not a valid DOM method—it should be getElementById().

Step-by-step Derivation:

  1. getElementById('test') returns the element with id='test' directly (not a collection) → can use .innerHTML immediately.
  2. getElementsByName('hacker') returns a NodeList of all elements with name='hacker' → must use [0] to access the first element before using .innerHTML.
  3. getElementsById() does not exist in the DOM API; this is a non-existent method.
  4. Option A: document.getElementById('test').innerHTML += ' Mr. Bob' → element.innerHTML = 'Hello' + ' Mr. Bob' = 'Hello Mr. Bob' ✓
  5. Option B: getElementsByName() returns NodeList, not an element → NodeList.innerHTML is undefined ✗
  6. Option C: getElementsById() is undefined (invalid method) ✗
  7. Option D: document.getElementsByName('hacker')[0].innerHTML += ' Mr. Bob' → element.innerHTML = 'Hello' + ' Mr. Bob' = 'Hello Mr. Bob' ✓