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