[Go to site: main page, start]

0% found this document useful (0 votes)
7 views11 pages

JavaScript Intermediate Level

The document provides a comprehensive guide on DOM manipulation in JavaScript, covering element selection, text and style changes, class management, event handling, and element creation/removal. It also includes sections on arrays and objects, advanced functions like closures and recursion, and error handling techniques. Key methods and common mistakes are summarized in tables for quick reference.

Uploaded by

rishicselab
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views11 pages

JavaScript Intermediate Level

The document provides a comprehensive guide on DOM manipulation in JavaScript, covering element selection, text and style changes, class management, event handling, and element creation/removal. It also includes sections on arrays and objects, advanced functions like closures and recursion, and error handling techniques. Key methods and common mistakes are summarized in tables for quick reference.

Uploaded by

rishicselab
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

DOM Manipulation in JavaScript

🔍 Selecting Elements
Use `getElementById`, `querySelector`, or `querySelectorAll` to
access DOM nodes.
const header = [Link]("main-header");
const buttons = [Link]("btn");
const paragraphs = [Link]("p");
const firstBtn = [Link](".btn");
const mainTitle = [Link]("#main-title");
const allBtns = [Link](".btn");
const forms = [Link];
const firstForm = [Link][0];
const allImages = [Link];
const allLinks = [Link];

const container = [Link]("container");


const children = [Link];
const firstChild = [Link];
const parent = [Link];

const button = [Link](".btn");


const form = [Link]("form");

const el = [Link]("div");
if ([Link](".active")) {
[Link]("Element is active");
}

✏️Changing Text & HTML


Use `textContent`, `innerHTML`, or `innerText` to change content.
[Link]("h1").textContent = "Updated!";
[Link]("div").innerHTML = "<p>New HTML content</p>";

🎨 Changing Styles
You can modify inline styles directly using the `style` object.
const box = [Link](".box");
[Link] = "blue";
[Link] = "none";
➕ Adding & Removing Classes
`classList` allows you to add, remove, or toggle CSS classes.
[Link]("active");
[Link]("hidden");
[Link]("dark-mode");

🧱 Creating Elements
You can dynamically create elements using `createElement` and
append them to the DOM.
const newDiv = [Link]("div");
[Link] = "Hello!";
[Link](newDiv);

🧼 Removing Elements
Use `remove()` or `removeChild()` to delete elements from the
DOM.
const button = [Link]("button");
[Link]();

🎯 Event Handling
Use `addEventListener` to react to user interactions.
const btn = [Link]("#submit");
[Link]("click", () => {
alert("Submitted!");
});

🔁 Looping through NodeLists


`querySelectorAll` returns a NodeList which can be looped using
`forEach`.
[Link]("li").forEach(item => {
[Link] = "blue";
});

🧬 Dataset & Attributes


Access custom `data-*` attributes or set HTML attributes using
`.dataset` or `.setAttribute()`.
const el = [Link]("[data-user]");
[Link]([Link]);
[Link]("title", "Tooltip");

🧩 Traversing DOM Tree


Navigate using properties like `parentElement`, `children`,
`nextElementSibling`, etc.
const item = [Link]("li");
[Link]([Link]);
[Link]([Link]);

📋 DOM Summary Table


Method/
Purpose Example Common M
Property
Selects first
querySelector matching querySelector(".box ") Using ID selector with `#` wrongly
element
Set HTML [Link] =
innerHTML Injecting untrusted HTML (XSS)
content "<p>Hi</p>"
[Link] Toggle class Forgetting to pass the second boolean
[Link](" dark ")
e() dynamically parameter when needed
Create new [Link](" div
createElement Not appending it after creation
DOM node ")
addEventListe [Link](" click ",
Bind events Assigning instead of adding (e.g., ` >ner fn)

JavaScript Event Handling Guide


🖱️addEventListener
Attaches an event handler to an element without overwriting
existing handlers.
const button = [Link]("button");
[Link]("click", () => {
[Link]("Button clicked!");
});

🔄 removeEventListener
Removes an event handler that was added using
`addEventListener`.
function handleClick() {
[Link]("Clicked!");
}
[Link]("click", handleClick);
[Link]("click", handleClick);

💡 Event Object
Every event handler receives an `event` object with details about
the event.
[Link]("keydown", (event) => {
[Link]([Link]); // e.g., "Enter"
});

🎯 Event Target
`[Link]` gives the element where the event actually
happened.
[Link]("ul").addEventListener("click", (e) => {
[Link]([Link]); // text of clicked <li>
});

📍 Event Delegation
Attach events to parent elements to handle future children using
`[Link]`.
[Link]("#parent").addEventListener("click", (e) => {
if ([Link](".child")) {
[Link]("Child clicked");
}
});

stopPropagation()
Prevents the event from bubbling up to parent elements.
[Link](".box").addEventListener("click", (e) => {
[Link]();
[Link]("Box clicked");
});

🚫 preventDefault()
Prevents the default action associated with the event (e.g., link
navigation).
[Link]("form").addEventListener("submit", (e) => {
[Link]();
[Link]("Form submission prevented.");
});

Once Option
Run the event handler only once using the `{ once: true }` option.
[Link]("click", () => {
[Link]("This runs once");
}, { once: true });

🧼 Passive Events
Tell the browser not to call `preventDefault()` for better
performance in scroll events.
[Link]("scroll", handleScroll, { passive: true });

📦 Inline Events (Not Recommended)


Old method of event binding directly in HTML. Avoid for separation
of concerns.
<button Me</button>

📝 Event Handling Summary Table


Concept Purpose Example Common Mistake
addEventListener Attach event click, submit Missing selector
Concept Purpose Example Common Mistake
Cancel default
preventDefault() form submission Calling too late
action
stopPropagation(
Prevent bubbling inside nested elements Confusing with preventDefault()
)
Actual clicked
[Link] use in delegation Confusing with `currentTarget`
element
for onboarding modals
{ once: true } Single-use handler Using with anonymous function and removing later
etc.

📚 JavaScript Arrays & Objects


Guide
📦 Creating Arrays
Arrays can be created using literals or constructors.
const arr1 = [1, 2, 3];
const arr2 = new Array(5);

🔁 Looping through Arrays


Use `for`, `forEach`, `map`, or `for...of` to iterate.
[Link](item => [Link](item));
for (const item of arr) {
[Link](item);
}

🧪 Common Array Methods


`push`, `pop`, `shift`, `unshift`, `map`, `filter`, `reduce` are
commonly used.
[Link](4);
[Link](x => x > 2);
[Link]((sum, x) => sum + x, 0);

🔍 Searching Arrays
Use `find`, `includes`, `indexOf`, or `some`.
[Link](3);
[Link](x => x === 5);

📐 Array Destructuring
Unpack values from arrays into distinct variables.
const [first, second] = [10, 20];

📦 Creating Objects
Objects can be created using literals or constructors.
const person = {
name: "Alice",
age: 30
};

🔍 Accessing Object Properties


Use dot or bracket notation to access values.
[Link]([Link]);
[Link](person["age"]);

🛠️Modifying Objects
Add or remove properties using assignment or `delete`.
[Link] = "developer";
delete [Link];

📐 Object Destructuring
Extract values from an object.
const obj = { x: 10, y: 20 };
const { x, y } = obj;

🔁 Looping through Objects


Use `for...in` or `[Link]()` to iterate.
for (let key in obj) {
[Link](key, obj[key]);
}
[Link](obj).forEach(([k, v]) => [Link](k, v));

🧠 Arrays & Objects Summary Table


Concept Purpose Example Common Mistake
map() Transform array [Link](x =>x+1) Using for side-effects
reduce() Aggregate values [Link]((a,b)=>a+b) Wrong initial value
object destructuring Extract keys const { x } = obj Key not found → `undefined`
for...in Loop through object for (let key in obj) Used on arrays (use for...of instead)
delete Remove object key delete [Link] Doesn’t affect prototype

⚙️Advanced Functions in
JavaScript
📦 Closures
Functions can remember the scope in which they were created even
after that scope has exited.
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
[Link](counter()); // 1
[Link](counter()); // 2

🧱 Higher-Order Functions
Functions that take other functions as arguments or return them.
function greet(name) {
return `Hello, ${name}`;
}
function processUserInput(callback) {
const name = "John";
return callback(name);
}
[Link](processUserInput(greet));

🌀 Recursion
A function calling itself to solve problems in smaller parts.
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
[Link](factorial(5)); // 120

🧩 Currying
Transforming a function with multiple arguments into a sequence of
unary functions.
function multiply(a) {
return function(b) {
return a * b;
};
}
const double = multiply(2);
[Link](double(5)); // 10

⏱ Debounce
Delays function execution until a certain time has passed without it
being called again.
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}

🚀 Throttle
Ensures a function is only called once in a specified time frame.
function throttle(fn, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}

🚨 Error Handling in JavaScript


❗ try-catch Block
Wrap risky code in `try` and catch errors gracefully using `catch`.
try {
const result = riskyFunction();
[Link](result);
} catch (error) {
[Link]("An error occurred:", [Link]);
}

🪝 finally Block
`finally` always runs after `try-catch`, whether there's an error or
not.
try {
[Link]("Start");
throw new Error("Oops!");
} catch (e) {
[Link]("Caught:", [Link]);
} finally {
[Link]("Cleanup tasks done.");
}

🚫 Throwing Errors
Use `throw` to raise your own custom errors.
function divide(a, b) {
if (b === 0) throw new Error("Division by zero is not allowed.");
return a / b;
}
try {
[Link](divide(10, 0));
} catch (e) {
[Link]([Link]);
}

🧪 Optional Chaining with Nullish Coalescing


Prevent runtime errors using `?.` and `??` for safer access.
const user = null;
[Link](user?.name ?? "Guest");

You might also like