JavaScript DOM Manipulation MCQs

1 min read

The Document Object Model (DOM) is a cross-platform programming interface that treats HTML and XML documents as a hierarchical tree structure of nodes and objects. JavaScript uses DOM APIs to interact with web pages dynamically allowing scripts to select elements, update text contents, modify inline styles, manage CSS classes, create or remove node elements, and handle user interactions like clicks and keystrokes. Mastering selection methods (querySelector, getElementById), content properties (textContent, innerHTML), event handling (addEventListener), and element insertion is crucial for modern front-end development and technical software engineering interviews.

1. What does DOM stand for in web development?

a) Document Object Model
b) Data Oriented Management
c) Digital Online Markup
d) Document Oriented Mechanism
Correct Answer: a) Document Object Model
Explanation:
DOM stands for Document Object Model, which represents the page so that programs can change the document structure, style, and content.

2. Which method returns the first element within the document that matches the specified selector?

a) getElementById()
b) querySelector()
c) querySelectorAll()
d) getElementsByClassName()
Correct Answer: b) querySelector()
Explanation:
querySelector() returns the first Element within the document that matches the specified CSS selector, or null if no matches are found.

3. What type of collection does document.querySelectorAll() return?

a) A live HTMLCollection
b) A static NodeList
c) A standard JavaScript Array
d) A live NodeList
Correct Answer: b) A static NodeList
Explanation:
querySelectorAll() returns a static NodeList, meaning subsequent changes to the DOM do not affect the contents of the collection.

4. What type of collection do methods like getElementsByClassName() and getElementsByTagName() return?

a) A static NodeList
b) A live HTMLCollection
c) A static Array
d) A frozen object
Correct Answer: b) A live HTMLCollection
Explanation:
HTMLCollections returned by getElementsByClassName and getElementsByTagName are live, meaning they automatically update when elements are added or removed.

5. Which property is used to get or set the HTML content inside an element?

a) innerText
b) textContent
c) innerHTML
d) outerHTML
Correct Answer: c) innerHTML
Explanation:
innerHTML gets or sets the HTML markup contained within the element.

6. What is the primary difference between innerText and textContent?

a) innerText is aware of CSS styling and won't return hidden text, whereas textContent returns all text regardless of visibility.
b) textContent only works on input fields.
c) innerText parses HTML tags, while textContent does not.
d) There is no difference between them.
Correct Answer: a) innerText is aware of CSS styling and won't return hidden text, whereas textContent returns all text regardless of visibility.
Explanation:
innerText takes CSS styling into account and triggers a reflow, while textContent gets the raw text of all nodes without rendering checks.

7. Which method is used to dynamically create a new HTML element in JavaScript?

a) document.newElement()
b) document.createElement()
c) document.makeElement()
d) document.addElement()
Correct Answer: b) document.createElement()
Explanation:
document.createElement() creates the specified HTML element specified by tagName.

8. How do you append a newly created element as the last child of a parent container?

a) parent.appendChild(child)
b) parent.insertLast(child)
c) parent.add(child)
d) parent.push(child)
Correct Answer: a) parent.appendChild(child)
Explanation:
appendChild() adds a node to the end of the list of children of a specified parent node.

9. Which property can be used to navigate to the parent node of a given DOM element?

a) parentElement
b) parentNode
c) Both parentElement and parentNode
d) upNode
Correct Answer: c) Both parentElement and parentNode
Explanation:
Both properties return the parent of the specified node, with parentElement returning null if the parent is not an Element node.

10. What is the purpose of element.classList.toggle('active')?

a) It always adds the 'active' class.
b) It always removes the 'active' class.
c) It adds the class if it is missing, or removes it if it is already present.
d) It checks if the class exists and returns a boolean.
Correct Answer: c) It adds the class if it is missing, or removes it if it is already present.
Explanation:
classList.toggle() behaves like a switch: adding the class if absent and removing it if present.

11. How do you remove an element directly from the DOM in modern JavaScript?

a) element.remove()
b) element.delete()
c) element.destroy()
d) element.drop()
Correct Answer: a) element.remove()
Explanation:
The Element.remove() method removes the element from the DOM children list of its parent.

12. Which method is used to attach an event handler to a DOM element?

a) element.attachEvent()
b) element.addEventListener()
c) element.on()
d) element.registerEvent()
Correct Answer: b) element.addEventListener()
Explanation:
addEventListener() is the standard W3C DOM method for registering an event handler on an element.

13. What is event bubbling?

a) Events propagate from the innermost target element outward up to the root document.
b) Events propagate from the root document down to the target element.
c) Events execute in a random asynchronous order.
d) Events automatically repeat every second.
Correct Answer: a) Events propagate from the innermost target element outward up to the root document.
Explanation:
Event bubbling is the phase where an event triggered on a child element bubbles up through its ancestors in the DOM tree.

14. What is event capturing (or trickling)?

a) Events propagate from the root document down to the target element before bubbling.
b) Events are captured and stored in local storage.
c) Events propagate from the target outward.
d) Events are prevented from firing.
Correct Answer: a) Events propagate from the root document down to the target element before bubbling.
Explanation:
During the capturing phase, the event starts from the window/document and travels down to the target element.

15. How do you stop an event from propagating further up or down the DOM tree?

a) event.preventDefault()
b) event.stopPropagation()
c) event.stopImmediate()
d) event.cancelBubble()
Correct Answer: b) event.stopPropagation()
Explanation:
stopPropagation() prevents further propagation of the current event in the bubbling or capturing phase.

16. What does event.preventDefault() do?

a) Stops event bubbling
b) Cancels the event if it is cancelable, meaning the default action belonging to the event will not occur
c) Deletes the event listener
d) Resets the form fields
Correct Answer: b) Cancels the event if it is cancelable, meaning the default action belonging to the event will not occur
Explanation:
preventDefault() stops browser default behaviors, such as following a link or submitting a form.

17. What is event delegation?

a) Delegating event handling to a single parent element to manage events on multiple child elements efficiently
b) Assigning multiple event listeners to a single button
c) Passing events between different web workers
d) Removing event listeners automatically
Correct Answer: a) Delegating event handling to a single parent element to manage events on multiple child elements efficiently
Explanation:
Event delegation leverages event bubbling to handle events at a higher level in the DOM, reducing memory overhead and supporting dynamic elements.

18. Which property on the event object refers to the element that actually triggered the event?

a) event.currentTarget
b) event.target
c) event.srcElement
d) event.explicitOriginalTarget
Correct Answer: b) event.target
Explanation:
event.target points to the DOM element that dispatched the event (the actual source where the user clicked/interacted).

19. What does event.currentTarget represent?

a) The element whose event listener is currently being traversed (the element attached to the listener)
b) The innermost child element
c) The browser window
d) The global event queue
Correct Answer: a) The element whose event listener is currently being traversed (the element attached to the listener)
Explanation:
event.currentTarget always refers to the element to which the event handler has been attached.

20. What is a DocumentFragment used for in DOM manipulation?

a) To store confidential passwords securely
b) To act as a lightweight, off-DOM container to batch multiple insertions and prevent frequent reflows/repaints
c) To parse JSON responses from APIs
d) To cache CSS stylesheets
Correct Answer: b) To act as a lightweight, off-DOM container to batch multiple insertions and prevent frequent reflows/repaints
Explanation:
DocumentFragment is not part of the main DOM tree. Appending children to it does not trigger reflow, making batch insertions highly performant.

21. Which method returns a DOMRect object providing information about the size of an element and its position relative to the viewport?

a) getElementPosition()
b) getBoundingClientRect()
c) getBoxMetrics()
d) getViewportCoords()
Correct Answer: b) getBoundingClientRect()
Explanation:
getBoundingClientRect() returns the bounding box properties (top, left, bottom, right, width, height) relative to the viewport.

22. How do you set an attribute on a DOM element?

a) element.attr('name', 'value')
b) element.setAttribute('name', 'value')
c) element.property('name', 'value')
d) element.define('name', 'value')
Correct Answer: b) element.setAttribute('name', 'value')
Explanation:
setAttribute() sets the value of an attribute on the specified element.

23. Which method is used to retrieve the value of a specific attribute on an element?

a) element.getAttribute('name')
b) element.findAttribute('name')
c) element.property('name')
d) element.read('name')
Correct Answer: a) element.getAttribute('name')
Explanation:
getAttribute() returns the value of a specified attribute on the element.

24. How do you access custom data attributes (e.g., data-user-id="123") in JavaScript?

a) element.getAttribute('data-user-id') or element.dataset.userId
b) element.data('user-id')
c) element.custom.userId
d) element.meta.userId
Correct Answer: a) element.getAttribute('data-user-id') or element.dataset.userId
Explanation:
Custom data attributes are accessible via getAttribute or camelCase properties on the element.dataset object.

25. What is a browser reflow (or layout)?

a) The process of recalculating the positions and geometries of elements in the document for rendering
b) Refreshing the browser tab automatically
c) Reloading JavaScript files from server cache
d) Garbage collection of DOM nodes
Correct Answer: a) The process of recalculating the positions and geometries of elements in the document for rendering
Explanation:
Reflow is the heavy computational process where the browser calculates layout geometries for element rendering.

26. What is a browser repaint?

a) Redrawing elements when their visual styling changes without affecting layout geometry
b) Clearing the canvas context
c) Re-downloading CSS stylesheets
d) Recompiling JavaScript scripts
Correct Answer: a) Redrawing elements when their visual styling changes without affecting layout geometry
Explanation:
Repaint occurs when changes are made to element styling (like background color or visibility) that don't alter layout dimensions.

27. Which property returns the child elements of an element as an HTMLCollection, excluding text and comment nodes?

a) childNodes
b) children
c) elementChildren
d) nodeList
Correct Answer: b) children
Explanation:
The children property returns only element nodes, whereas childNodes returns all child nodes including text, whitespace, and comments.

28. How do you check if an element has any child nodes?

a) element.hasChildNodes()
b) element.hasChildren()
c) element.containsChildren()
d) element.childCount > 0
Correct Answer: a) element.hasChildNodes()
Explanation:
hasChildNodes() returns a boolean value indicating whether the given node has child nodes.

29. Which method inserts a set of Node objects or string objects after the last child of the element?

a) element.append()
b) element.appendChild()
c) element.insertAfter()
d) element.pushChild()
Correct Answer: a) element.append()
Explanation:
Element.append() allows appending multiple nodes and strings (unlike appendChild which only accepts a single Node object and returns it).

30. What does element.prepend() do?

a) Inserts nodes or strings before the first child of the element
b) Inserts nodes at the very end of the body
c) Replaces the element itself
d) Deletes the first child
Correct Answer: a) Inserts nodes or strings before the first child of the element
Explanation:
prepend() inserts a set of Node or string objects before the first child of the parent element.

31. How do you replace an existing child element with a new child element?

a) parent.replaceChild(newChild, oldChild)
b) parent.swap(oldChild, newChild)
c) oldChild.replaceWith(newChild)
d) Both a and c
Correct Answer: d) Both a and c
Explanation:
Both parent.replaceChild() and modern element.replaceWith() can be used to replace DOM nodes.

32. What is the return value of element.matches('.my-class')?

a) A boolean (true if the element would be selected by the specified CSS selector string, otherwise false)
b) The matched element object
c) An array of matching classes
d) An integer count
Correct Answer: a) A boolean (true if the element would be selected by the specified CSS selector string, otherwise false)
Explanation:
element.matches() checks if the element is selectable by the specified CSS selector query.

33. Which method traverses upwards from the element itself (and through its ancestors) until it finds a node that matches the specified CSS selector?

a) element.closest()
b) element.parentQuery()
c) element.findAncestor()
d) element.searchUp()
Correct Answer: a) element.closest()
Explanation:
element.closest() traverses the element and its parents (heading toward the document root) until it finds a node matching the provided selector.

34. How do you get computed CSS styles that are actually applied to an element by the browser after all stylesheets and cascades take effect?

a) window.getComputedStyle(element)
b) element.style
c) element.currentCSS
d) document.getStyles(element)
Correct Answer: a) window.getComputedStyle(element)
Explanation:
window.getComputedStyle() returns an object containing the computed values of all CSS properties of an element.

35. What is the limitation of accessing styles via `element.style.property`?

a) It only retrieves inline styles set directly on the element's style attribute, not styles from external or internal CSS stylesheets.
b) It is completely deprecated in modern browsers.
c) It only works on block-level elements.
d) It returns styles as a JSON string.
Correct Answer: a) It only retrieves inline styles set directly on the element's style attribute, not styles from external or internal CSS stylesheets.
Explanation:
element.style only reflects inline styles, which is why getComputedStyle is required for stylesheets.

36. What is the purpose of element.focus()?

a) To set keyboard focus on the specified element
b) To blur background elements
c) To zoom the camera onto the element
d) To trigger a click event
Correct Answer: a) To set keyboard focus on the specified element
Explanation:
element.focus() gives focus to the element if it can be focused (such as input fields, buttons, or elements with tabindex).

37. How do you programmatically trigger a click event on a button element?

a) button.click()
b) button.trigger('click')
c) button.fireEvent('click')
d) button.dispatch('click')
Correct Answer: a) button.click()
Explanation:
The HTMLElement.click() method simulates a mouse click on an element.

38. How do you create and dispatch a custom event in modern JavaScript?

a) const event = new CustomEvent('myevent', { detail: { id: 1 } }); element.dispatchEvent(event);
b) document.fireCustomEvent('myevent', { id: 1 })
c) element.triggerCustom('myevent', 1)
d) Event.create('myevent')
Correct Answer: a) const event = new CustomEvent('myevent', { detail: { id: 1 } }); element.dispatchEvent(event);
Explanation:
CustomEvent constructor and dispatchEvent() are the standard APIs for creating and emitting custom application events.

39. What is the purpose of the passive option in addEventListener (e.g., `{ passive: true }`)?

a) It signals to the browser that the listener will never call preventDefault(), improving scroll performance.
b) It makes the event listener run asynchronously in a web worker.
c) It disables event bubbling automatically.
d) It prevents memory leaks on unmount.
Correct Answer: a) It signals to the browser that the listener will never call preventDefault(), improving scroll performance.
Explanation:
Passive event listeners allow browsers to immediately scroll without waiting for touch/wheel event handlers to finish executing.

40. What is the purpose of the once option in addEventListener (`{ once: true }`)?

a) It automatically removes the event listener after it is triggered for the first time.
b) It restricts the event to firing only once per session.
c) It prevents double clicks.
d) It executes the event on page load.
Correct Answer: a) It automatically removes the event listener after it is triggered for the first time.
Explanation:
Setting once: true ensures the listener is unregistered automatically right after its first invocation.

41. Which property gives the height of an element including padding, border, but excluding margin?

a) offsetHeight
b) clientHeight
c) scrollHeight
d) getBoundingClientRect().height
Correct Answer: a) offsetHeight
Explanation:
offsetHeight returns the outer height of an element, including CSS height, padding, and borders, plus horizontal scrollbar if rendered.

42. What does clientHeight measure?

a) Inner height of an element including padding, but excluding borders, margins, and horizontal scrollbars
b) Total scrollable height
c) Height including borders
d) Viewport window height
Correct Answer: a) Inner height of an element including padding, but excluding borders, margins, and horizontal scrollbars
Explanation:
clientHeight represents the inner height of an element in pixels, including padding but excluding borders and margins.

43. What does scrollHeight measure?

a) The entire content height of an element, including content not visible on the screen due to overflow
b) The visible viewport height
c) The border height
d) The fixed CSS height property
Correct Answer: a) The entire content height of an element, including content not visible on the screen due to overflow
Explanation:
scrollHeight measures the total height of element content including overflow content that requires scrolling.

44. Which property represents the number of pixels that an element's content is scrolled vertically?

a) scrollTop
b) scrollOffset
c) verticalScroll
d) scrollY
Correct Answer: a) scrollTop
Explanation:
scrollTop gets or sets the number of pixels that an element's content is scrolled vertically.

45. How do you check if a checkbox input element is checked in JavaScript?

a) checkbox.checked
b) checkbox.value === 'true'
c) checkbox.getAttribute('checked')
d) checkbox.isSelected()
Correct Answer: a) checkbox.checked
Explanation:
The checked boolean property accurately reflects whether a checkbox or radio button is currently checked.

46. Which event fires on an input or textarea element immediately whenever its value changes?

a) change
b) input
c) keypress
d) modify
Correct Answer: b) input
Explanation:
The input event fires synchronously whenever the value of an input, select, or textarea element is changed by user interaction.

47. When does the 'change' event fire on an input element?

a) On every single keystroke
b) When the element loses focus after its value has been changed (or when a selection is committed)
c) When the page loads
d) When the mouse hovers over it
Correct Answer: b) When the element loses focus after its value has been changed (or when a selection is committed)
Explanation:
Unlike the input event, the change event typically fires when the control loses focus or when a commit action occurs (e.g., selecting a dropdown option).

48. How do you prevent form submission when a submit button is clicked?

a) form.prevent()
b) event.preventDefault() inside the form's 'submit' event listener
c) form.cancel()
d) event.stopPropagation()
Correct Answer: b) event.preventDefault() inside the form's 'submit' event listener
Explanation:
Calling event.preventDefault() inside a submit event listener prevents the browser from performing its default form submission request.

49. What is the purpose of element.cloneNode(true)?

a) It creates a deep clone of the element, including all of its descendants and child nodes.
b) It creates a shallow clone without children.
c) It clones the element and binds all event listeners.
d) It deletes the element.
Correct Answer: a) It creates a deep clone of the element, including all of its descendants and child nodes.
Explanation:
Passing true to cloneNode() performs a deep clone; passing false (or omitting it) performs a shallow clone of only the node itself.

50. Which property gives the node type of a DOM node as a numeric constant (e.g., 1 for Element, 3 for Text)?

a) nodeType
b) nodeKind
c) typeID
d) elementCategory
Correct Answer: a) nodeType
Explanation:
nodeType returns an integer representing the type of the node (Node.ELEMENT_NODE is 1, Node.TEXT_NODE is 3, etc.).

51. What is the nodeName of an HTML paragraph element () in uppercase?

a) P
b) PARAGRAPH
c) HTMLPARAGRAPHELEMENT
d) TEXT
Correct Answer: a) P
Explanation:
nodeName for HTML elements returns their tag name in uppercase (e.g., 'DIV', 'P', 'SPAN').

52. How do you insert HTML markup directly at a specified position relative to an element (e.g., beforebegin, afterbegin, beforeend, afterend)?

a) element.insertAdjacentHTML(position, text)
b) element.writeHTML()
c) element.setHTML()
d) element.inject()
Correct Answer: a) element.insertAdjacentHTML(position, text)
Explanation:
insertAdjacentHTML parses the specified text as HTML and inserts the resulting nodes into the DOM tree at a specified position.

53. What does element.hasAttribute('disabled') return?

a) A boolean indicating whether the element has the specified attribute
b) The string value of the attribute
c) A number representing attribute count
d) Null if missing
Correct Answer: a) A boolean indicating whether the element has the specified attribute
Explanation:
hasAttribute() returns true if the attribute is present on the element, and false otherwise.

54. How do you remove an attribute from an element?

a) element.removeAttribute('name')
b) element.deleteAttribute('name')
c) element.attr.remove('name')
d) element.clearAttribute('name')
Correct Answer: a) element.removeAttribute('name')
Explanation:
removeAttribute() removes the attribute with the specified name from the element.

55. What is the role of the 'load' event on the window object?

a) It fires when the whole page has loaded, including all dependent resources such as stylesheets and images.
b) It fires as soon as the HTML document has been parsed, without waiting for stylesheets or images.
c) It fires when a user leaves the page.
d) It fires when an image fails to load.
Correct Answer: a) It fires when the whole page has loaded, including all dependent resources such as stylesheets and images.
Explanation:
window 'load' waits for complete asset loading, unlike DOMContentLoaded which fires earlier.

56. When does the 'DOMContentLoaded' event fire?

a) When the initial HTML document has been completely parsed and the DOM tree is built, without waiting for stylesheets, images, and subframes to finish loading.
b) When all images and stylesheets are fully downloaded.
c) When the user closes the browser tab.
d) When JavaScript execution completes.
Correct Answer: a) When the initial HTML document has been completely parsed and the DOM tree is built, without waiting for stylesheets, images, and subframes to finish loading.
Explanation:
DOMContentLoaded is ideal for running scripts that interact with DOM elements as soon as the markup is parsed.

57. How do you check if an element contains another element as a descendant in the DOM tree?

a) parent.contains(child)
b) parent.hasChild(child)
c) parent.includes(child)
d) child.isInside(parent)
Correct Answer: a) parent.contains(child)
Explanation:
Node.contains() returns a boolean value indicating whether a node is a descendant of a specified node.

58. Which property returns the previous sibling node of a specified node, including text and comment nodes?

a) previousSibling
b) previousElementSibling
c) priorNode
d) leftSibling
Correct Answer: a) previousSibling
Explanation:
previousSibling returns the previous node in the tree, which may be a text node or whitespace.

59. What is the difference between nextSibling and nextElementSibling?

a) nextSibling returns any node (including whitespace/text), while nextElementSibling skips non-element nodes to return the next sibling Element.
b) nextElementSibling only works in Internet Explorer.
c) nextSibling returns parent elements.
d) There is no difference.
Correct Answer: a) nextSibling returns any node (including whitespace/text), while nextElementSibling skips non-element nodes to return the next sibling Element.
Explanation:
Element-specific traversal properties ignore text and comment nodes.

60. What is the global object representing the browser window in client-side JavaScript?

a) window
b) document
c) navigator
d) global
Correct Answer: a) window
Explanation:
The window object represents the browser window containing the DOM document.

61. How do you access the root element of a document?

a) document.documentElement
b) document.rootElement
c) document.html
d) document.body.parent
Correct Answer: a) document.documentElement
Explanation:
document.documentElement is a read-only property that returns the root element of the document (such as for HTML documents).

62. How do you access the element of a document?

a) document.body
b) document.getElementsByTagName('body')[0]
c) Both a and b
d) document.rootBody
Correct Answer: c) Both a and b
Explanation:
document.body is a direct shortcut property to access the element.

63. What does document.head return?

a) The element of the current document
b) The title tag string
c) The HTTP response headers
d) The browser vendor name
Correct Answer: a) The element of the current document
Explanation:
document.head returns the element of the document.

64. How do you check if an element has any classes using classList?

a) element.classList.length > 0
b) element.hasClasses()
c) element.classList.exists()
d) element.classCount > 0
Correct Answer: a) element.classList.length > 0
Explanation:
classList implements a DOMTokenList, which has a length property representing the number of classes applied.

65. Which method on classList checks if a specific class is present on an element?

a) classList.contains('className')
b) classList.has('className')
c) classList.includes('className')
d) classList.check('className')
Correct Answer: a) classList.contains('className')
Explanation:
classList.contains() returns true if the element's class list contains the specified class name.

66. What is the purpose of element.blur()?

a) To remove keyboard focus from the specified element
b) To apply a CSS blur filter
c) To hide the element
d) To clear input values
Correct Answer: a) To remove keyboard focus from the specified element
Explanation:
element.blur() removes focus from the currently focused element.

67. Which event fires on an input element when the user selects some text inside it?

a) select
b) focus
c) highlight
d) choose
Correct Answer: a) select
Explanation:
The select event fires when text has been selected in a or element.

68. What is the purpose of the 'submit' event on form elements?

a) It fires when a form is submitted (via button click or enter key press in input fields).
b) It fires whenever any input changes.
c) It fires when the reset button is clicked.
d) It validates password strength.
Correct Answer: a) It fires when a form is submitted (via button click or enter key press in input fields).
Explanation:
The submit event fires on a form when it is submitted.

69. How do you reset a form programmatically in JavaScript?

a) form.reset()
b) form.clear()
c) form.initialize()
d) form.empty()
Correct Answer: a) form.reset()
Explanation:
The HTMLFormElement.reset() method restores a form's default values.

70. What does the 'scroll' event fire on?

a) Elements or windows when their viewable content is scrolled
b) Only mouse scroll wheel movements
c) Keyboard arrow key presses
d) Page load completion
Correct Answer: a) Elements or windows when their viewable content is scrolled
Explanation:
The scroll event fires when the document view or an element has been scrolled.

71. What is the purpose of window.scrollTo(x, y)?

a) To scroll the window to a particular set of coordinates in the document
b) To scroll by a relative pixel offset
c) To lock scrolling
d) To reset scroll position to zero
Correct Answer: a) To scroll the window to a particular set of coordinates in the document
Explanation:
window.scrollTo scrolls the window to absolute coordinates (x, y).

72. How do you scroll a window by a specific relative amount of pixels?

a) window.scrollBy(x, y)
b) window.moveBy(x, y)
c) window.shift(x, y)
d) window.offset(x, y)
Correct Answer: a) window.scrollBy(x, y)
Explanation:
window.scrollBy scrolls the document by the specified number of pixels relative to its current scroll position.

73. What does element.scrollIntoView() do?

a) Scrolls the parent container of the element so that the element is visible in the browser viewport
b) Centers the element on the screen with animation
c) Zooms into the element
d) Hides elements outside the viewport
Correct Answer: a) Scrolls the parent container of the element so that the element is visible in the browser viewport
Explanation:
scrollIntoView scrolls the element's parent container until the element is brought into the visible area of the browser.

74. What is the purpose of the 'resize' event on the window object?

a) It fires when the browser window has been resized.
b) It fires when images are resized.
c) It fires when fonts change scale.
d) It fires when device orientation changes.
Correct Answer: a) It fires when the browser window has been resized.
Explanation:
The resize event is sent to the window when the document view (window) is resized.

75. How do you check if an element is currently displayed or hidden using inline/computed styles?

a) window.getComputedStyle(element).display === 'none' or element.hidden
b) element.isVisible()
c) element.showState === false
d) element.displayCheck()
Correct Answer: a) window.getComputedStyle(element).display === 'none' or element.hidden
Explanation:
Checking computed display property or the hidden boolean property determines visibility.

76. What is the difference between visibility: hidden and display: none?

a) display: none removes the element from layout calculation entirely, whereas visibility: hidden hides the element but preserves its layout space.
b) visibility: hidden removes the element from the DOM.
c) display: none only works on images.
d) There is no difference.
Correct Answer: a) display: none removes the element from layout calculation entirely, whereas visibility: hidden hides the element but preserves its layout space.
Explanation:
display: none causes reflow by removing the element from the document layout, while visibility: hidden leaves an empty structural gap.

77. How do you select all elements with a specific class name in modern JavaScript?

a) document.querySelectorAll('.my-class')
b) document.getElementsByClassName('my-class')
c) Both a and b
d) document.findClass('my-class')
Correct Answer: c) Both a and b
Explanation:
querySelectorAll returns a static NodeList, while getElementsByClassName returns a live HTMLCollection.

78. What does document.getElementById('header') expect as its argument?

a) The string ID of the element without the '#' symbol
b) A CSS selector string including '#' (e.g., '#header')
c) An element object
d) A class name
Correct Answer: a) The string ID of the element without the '#' symbol
Explanation:
getElementById takes the ID string directly without any leading hash '#' symbol.

79. Which method removes an event listener that was previously added with addEventListener?

a) removeEventListener()
b) deleteEventListener()
c) off()
d) detachEvent()
Correct Answer: a) removeEventListener()
Explanation:
removeEventListener removes an event listener previously registered with addEventListener.

80. Why must the exact same callback reference be passed to removeEventListener as was passed to addEventListener?

a) Because JavaScript identifies listeners by reference; anonymous functions cannot be removed because their references cannot be addressed.
b) It is a security feature of the V8 engine.
c) To prevent garbage collection.
d) It is not required; anonymous functions can be removed by name.
Correct Answer: a) Because JavaScript identifies listeners by reference; anonymous functions cannot be removed because their references cannot be addressed.
Explanation:
To remove a listener, the exact function reference used during addition must be passed to removeEventListener.

81. What is the purpose of event.timeStamp?

a) Returns the time (in milliseconds) at which the event was created
b) Returns the current system date string
c) Measures network latency
d) Tracks animation frame rate
Correct Answer: a) Returns the time (in milliseconds) at which the event was created
Explanation:
timeStamp represents the epoch time when the event was generated.

82. What does element.innerHTML = '' do?

a) Clears all child elements and text content inside the element efficiently
b) Throws a syntax error
c) Deletes the element from the DOM
d) Adds an empty space node
Correct Answer: a) Clears all child elements and text content inside the element efficiently
Explanation:
Setting innerHTML to an empty string wipes out all internal descendants of the element.

83. Which property allows access to form controls within a form element as a named or indexed collection?

a) form.elements
b) form.controls
c) form.inputs
d) form.children
Correct Answer: a) form.elements
Explanation:
form.elements returns an HTMLFormControlsCollection of all form controls contained in the element.

84. How do you select a radio button group value in JavaScript?

a) By querying checked inputs, e.g., document.querySelector('input[name="gender"]:checked').value
b) By calling radioGroup.getValue()
c) By checking form.radio.value directly
d) By accessing window.selectedRadio
Correct Answer: a) By querying checked inputs, e.g., document.querySelector('input[name="gender"]:checked').value
Explanation:
Using a CSS pseudo-class :checked selector is the standard way to retrieve the active radio button's value.

85. What is the return value of element.matches() if the element does not match the selector?

a) false
b) null
c) -1
d) undefined
Correct Answer: a) false
Explanation:
element.matches() returns true or false based on whether the selector matches the element.

86. What does the blur event indicate when attached to an input field?

a) The input field has lost focus.
b) The input field has gained focus.
c) The input value has been submitted.
d) The input text has been blurred with CSS.
Correct Answer: a) The input field has lost focus.
Explanation:
The blur event fires when an element has lost focus.

87. What does the focus event indicate when attached to an input field?

a) The input field has received focus.
b) The user is typing.
c) The form is submitted.
d) The page finished loading.
Correct Answer: a) The input field has received focus.
Explanation:
The focus event fires when an element has received focus.

88. What is delegation useful for when handling lists with hundreds of dynamically added items?

a) It avoids attaching individual event listeners to every single item, saving memory and supporting new items automatically.
b) It makes list items render faster in CSS.
c) It encrypts list item data.
d) It prevents list items from being deleted.
Correct Answer: a) It avoids attaching individual event listeners to every single item, saving memory and supporting new items automatically.
Explanation:
Event delegation reduces listener overhead and automatically handles dynamically injected elements.

89. How do you check if an element is enabled or disabled in JavaScript?

a) element.disabled (returns true if disabled)
b) element.isEnabled()
c) element.status === 'active'
d) element.getAttribute('active')
Correct Answer: a) element.disabled (returns true if disabled)
Explanation:
The disabled property reflects whether form control elements are disabled.

90. What does element.tabIndex return if tab indexing is not explicitly set?

a) -1 or 0 depending on whether the element is naturally focusable
b) Null
c) Undefined
d) 100
Correct Answer: a) -1 or 0 depending on whether the element is naturally focusable
Explanation:
tabIndex returns the tab order of the element.

91. How do you read or write the text content of an input field?

a) input.value
b) input.textContent
c) input.innerHTML
d) input.text
Correct Answer: a) input.value
Explanation:
Form input controls store user entries in their .value property, not textContent or innerHTML.

92. Which method is used to insert a node before a specified reference child node within a parent?

a) parent.insertBefore(newNode, referenceNode)
b) parent.insertFirst(newNode)
c) parent.addBefore(referenceNode, newNode)
d) parent.prependChild(newNode)
Correct Answer: a) parent.insertBefore(newNode, referenceNode)
Explanation:
insertBefore() inserts a node before the reference node as a child of a specified parent.

93. What happens if the referenceNode argument in parent.insertBefore(newNode, referenceNode) is null?

a) The newNode is inserted at the end of the child list (acting like appendChild).
b) An error is thrown.
c) Nothing happens.
d) The newNode is inserted at the very beginning.
Correct Answer: a) The newNode is inserted at the end of the child list (acting like appendChild).
Explanation:
According to the DOM specification, if referenceNode is null, newNode is inserted at the end of the child nodes.

94. What does document.open() do in DOM manipulation contexts?

a) Opens a document stream for writing (document.write)
b) Opens a popup window
c) Opens a file dialog
d) Connects to a WebSocket
Correct Answer: a) Opens a document stream for writing (document.write)
Explanation:
document.open() opens a document stream for writing via document.write().

95. Why is document.write() generally discouraged in modern web development?

a) It can wipe out the entire document if called after the page has finished loading, and harms performance.
b) It only works in Safari.
c) It causes syntax errors in ES6 modules.
d) It requires jQuery.
Correct Answer: a) It can wipe out the entire document if called after the page has finished loading, and harms performance.
Explanation:
document.write blocks parsing and can overwrite loaded DOM contents if invoked post-load.

96. How do you check if an element is the active (focused) element in the document?

a) document.activeElement === element
b) element.hasFocus()
c) element.isActive
d) document.hasFocus(element)
Correct Answer: a) document.activeElement === element
Explanation:
document.activeElement returns the DOM element that currently has focus.

97. What is the purpose of window.getSelection()?

a) Returns a Selection object representing the range of text selected by the user
b) Returns selected form checkboxes
c) Returns highlighted DOM elements
d) Returns CSS selector matches
Correct Answer: a) Returns a Selection object representing the range of text selected by the user
Explanation:
window.getSelection() represents the text selection highlight made by the user in the document.

98. How do you read the computed font size of an element?

a) window.getComputedStyle(element).fontSize
b) element.style.fontSize
c) element.fontMetric
d) document.getFontSize(element)
Correct Answer: a) window.getComputedStyle(element).fontSize
Explanation:
Computed font size is retrieved via window.getComputedStyle.

99. What is the primary benefit of using classList over modifying className directly?

a) classList provides convenient helper methods like add, remove, toggle, and contains without needing manual string parsing.
b) classList runs 10x faster in all benchmarks.
c) className is deprecated and removed from modern specs.
d) classList allows direct CSS injection.
Correct Answer: a) classList provides convenient helper methods like add, remove, toggle, and contains without needing manual string parsing.
Explanation:
classList avoids string manipulation errors when managing multiple CSS classes on an element.

100. What does element.id return?

a) The string value of the element's id attribute
b) A unique internal memory hash
c) A numeric index in the DOM tree
d) The tag name
Correct Answer: a) The string value of the element's id attribute
Explanation:
The id property gets or sets the element's identifier.

101. Can an element have multiple class names separated by spaces in its className property?

a) Yes
b) No, only one class is ever permitted per element
c) Only if using SVG elements
d) Only in strict mode
Correct Answer: a) Yes
Explanation:
Multiple classes can be assigned separated by whitespace in className.

102. What does element.tagName return for an HTML anchor tag ()?

a) "A"
b) "ANCHOR"
c) "a"
d) "LINK"
Correct Answer: a) "A"
Explanation:
tagName returns the element's tag name in uppercase string format.

103. How do you determine the number of child elements contained within a parent element?

a) parent.childElementCount
b) parent.children.length
c) Both a and b
d) parent.size
Correct Answer: c) Both a and b
Explanation:
Both childElementCount and children.length provide the count of child element nodes.

104. What is the final outcome of mastering JavaScript DOM manipulation for frontend developers?

a) The ability to dynamically build interactive user interfaces, handle user events, and optimize browser rendering performance
b) The ability to manage SQL database migrations
c) The ability to configure network routers
d) The ability to compile native binaries
Correct Answer: a) The ability to dynamically build interactive user interfaces, handle user events, and optimize browser rendering performance
Explanation:
DOM mastery is essential for building dynamic web apps and front-end architectures.
← Previous: JavaScript Closures MCQs for Senior Developer Interviews
Next →: JavaScript Error Handling MCQs for Developer Interviews & Certification
NewTop Python Fundamentals MCQs & Answers for Beginners

Top Python Fundamentals MCQs & Answers for Beginners

Python is a dynamically typed, high-level programming language created by Guido van Rossum in 1991. Renowned for its clear syntax…

By MCQs Generator
NewJavaScript Asynchronous Programming MCQs

JavaScript Asynchronous Programming

Asynchronous programming in JavaScript enables non-blocking execution, allowing long-running operations such as network requests, file reading, or timers to run…

By MCQs Generator
NewPython Functions MCQs

Python Functions MCQs

Functions in Python are reusable blocks of code designed to perform a specific task, promoting code modularity, readability, and DRY…

By MCQs Generator