Back to Exercises

DOM & Events (Real Website Use)

20 Exercises Available

Buttons, forms, validation, event delegation — frontend essentials.

1.Easy

Toggle Password Visibility

Create a function `togglePassword(inputEl, btnEl)` that toggles input type "password" ↔ "text" and updates button text.

Sample Output:

togglePassword(inputEl, btnEl)
// If inputEl.type === "password":
//   inputEl.type => "text", btnEl.textContent => "Hide"
// If inputEl.type === "text":
//   inputEl.type => "password", btnEl.textContent => "Show"
View Solution
2.Medium

Form: Required Fields Validation

Create a function `validateRequired(formEl, names)`. Given input names list, set `data-error="Required"` on empty fields and return boolean.

Sample Output:

validateRequired(formEl, ["email", "password"])
// If email empty: formEl.elements.namedItem("email").getAttribute("data-error") => "Required", returns false
// If all filled: returns true
View Solution
3.Medium

Event Delegation: List Click

Given `<ul id="list">`, add single click listener on UL and detect which `<li data-id>` clicked. Return clicked id via callback.

Sample Output:

onListItemClick(ul, (id) => console.log(id))
// Click on <li data-id="123"> → callback called with "123"
// Click on <li data-id="456"> → callback called with "456"
View Solution
4.Easy

Auto Character Counter (textarea)

Function `bindCounter(textarea, counterEl, max)` banao jo live count dikhaye and overflow pe red class add kare.

Sample Output:

bindCounter(textarea, counterEl, 100)
// Typing "Hello" (5 chars): counterEl.textContent => "5/100", no red class
// Typing 150 chars: counterEl.textContent => "150/100", red class added
View Solution
5.Medium

Copy to Clipboard (button)

Create a function `copyText(text)` that copies to clipboard. Return success/fail boolean.

Sample Output:

await copyText("Hello World") => true (if successful)
await copyText("test") => false (if clipboard API unavailable)
View Solution
6.Easy

Toggle Class on Element

Function `toggleClass(el, className)` banao jo element pe class toggle kare. Example: toggleClass(buttonEl, "active") → class add/remove karega

Sample Output:

toggleClass(buttonEl, "active")
// If class exists: removes it
// If class doesn't exist: adds it
View Solution
7.Medium

Get All Form Values as Object

Function `getFormData(formEl)` banao jo form ke sabhi input values ko object me return kare. Example: getFormData(form) => {name: "John", email: "john@example.com"}

Sample Output:

getFormData(formEl) => {name: "John", email: "john@example.com"}
// Returns object with all form field values
View Solution
8.Easy

Set Multiple Attributes

Function `setAttributes(el, attrs)` banao jo element pe multiple attributes set kare. Example: setAttributes(imgEl, {src: "image.jpg", alt: "Image"})

Sample Output:

setAttributes(imgEl, {src: "image.jpg", alt: "Image"})
// Sets both src and alt attributes
View Solution
9.Medium

Check if Element is Visible

Function `isVisible(el)` banao jo check kare ki element visible hai ya nahi. Example: isVisible(divEl) => true/false

Sample Output:

isVisible(divEl) => true (if visible)
isVisible(hiddenEl) => false (if hidden)
View Solution
10.Easy

Scroll Element into View

Function `scrollIntoView(el, options)` banao jo element ko viewport me scroll kare. Example: scrollIntoView(buttonEl, {behavior: "smooth"})

Sample Output:

scrollIntoView(buttonEl, {behavior: "smooth"})
// Smoothly scrolls element into view
View Solution
11.Easy

Prevent Default and Stop Propagation

Function `handleEvent(e, handler)` banao jo event ko handle kare with preventDefault aur stopPropagation. Example: handleEvent(e, () => console.log("clicked"))

Sample Output:

handleEvent(e, () => console.log("clicked"))
// Prevents default, stops propagation, then calls handler
View Solution
12.Medium

Create Element with Attributes and Children

Function `createElement(tag, attrs, children)` banao jo element create kare with attributes aur children. Example: createElement("div", {class: "container"}, ["Hello"])

Sample Output:

createElement("div", {class: "container"}, ["Hello"]) => <div class="container">Hello</div>
View Solution
13.Hard

Remove All Event Listeners (pattern)

Function `removeAllListeners(el, eventType)` banao jo element se sabhi listeners remove kare. Note: Clone element to remove all listeners.

Sample Output:

removeAllListeners(buttonEl, "click")
// Removes all click listeners by cloning element
View Solution
14.Medium

Get Element Position (offset)

Function `getElementPosition(el)` banao jo element ki position return kare relative to document. Example: getElementPosition(divEl) => {x: 100, y: 200}

Sample Output:

getElementPosition(divEl) => {x: 100, y: 200}
// Returns position relative to document
View Solution
15.Easy

Check if Element Contains Another

Function `contains(parent, child)` banao jo check kare ki parent element child ko contain karta hai ya nahi. Example: contains(parentEl, childEl) => true/false

Sample Output:

contains(parentEl, childEl) => true (if parent contains child)
contains(parentEl, otherEl) => false (if not)
View Solution
16.Easy

Get Selected Options from Select

Function `getSelectedOptions(selectEl)` banao jo select element se selected options return kare. Example: getSelectedOptions(selectEl) => ["option1", "option2"]

Sample Output:

getSelectedOptions(selectEl) => ["option1", "option2"]
// Returns array of selected option values
View Solution
17.Easy

Disable/Enable Form Elements

Function `setFormDisabled(formEl, disabled)` banao jo form ke sabhi elements ko disable/enable kare. Example: setFormDisabled(formEl, true) → sabhi inputs disable

Sample Output:

setFormDisabled(formEl, true)
// Disables all form elements
setFormDisabled(formEl, false)
// Enables all form elements
View Solution
18.Easy

Get Element Text Content (trimmed)

Function `getTextContent(el)` banao jo element ka text content return kare (trimmed). Example: getTextContent(divEl) => "Hello World"

Sample Output:

getTextContent(divEl) => "Hello World"
// Returns trimmed text content
View Solution
19.Easy

Set Element InnerHTML Safely

Function `setInnerHTML(el, html)` banao jo element ka innerHTML set kare with validation. Example: setInnerHTML(divEl, "<p>Hello</p>")

Sample Output:

setInnerHTML(divEl, "<p>Hello</p>")
// Sets innerHTML to provided HTML string
View Solution
20.Easy

Check if Element has Class

Function `hasClass(el, className)` banao jo check kare ki element pe class hai ya nahi. Example: hasClass(buttonEl, "active") => true/false

Sample Output:

hasClass(buttonEl, "active") => true (if class exists)
hasClass(buttonEl, "inactive") => false (if not)
View Solution