Different Ways to Access DOM Elements in JavaScript While learning JavaScript, one of the first things that clicked for me was this: 👉 The browser becomes powerful when JavaScript can talk to the DOM. The DOM (Document Object Model) represents the structure of a web page, and accessing elements correctly is the first step to making pages interactive. Here are the most common ways 👇 ✅ 1️⃣ getElementById() Accesses a single element using its unique ID. document.getElementById("header"); ✔ Fast and straightforward ✔ Best when element ID is unique ✅ 2️⃣ getElementsByClassName() Selects elements based on class name. document.getElementsByClassName("card"); ✔ Returns a collection ✔ Useful when multiple elements share styling ✅ 3️⃣ getElementsByTagName() Selects elements using HTML tag names. document.getElementsByTagName("p"); ✔ Useful for generic selections ✔ Returns multiple elements ✅ 4️⃣ querySelector() Selects the first matching element using CSS selectors. document.querySelector(".card"); ✔ Flexible ✔ Supports CSS selector syntax ✅ 5️⃣ querySelectorAll() Selects all matching elements. document.querySelectorAll(".card"); ✔ Modern and commonly used ✔ Returns a NodeList 💡 My learning takeaway: Earlier, JavaScript felt like just logic. But once I started interacting with DOM elements, it felt like giving life to the UI. Small concepts like this make a big difference when moving towards frontend and full stack development. Which DOM selection method do you use most in your projects? 👇 #JavaScript #FrontendDevelopment #WebDevelopment #DOM #LearningJourney #FullStackDeveloper #Programming #SoftwareEngineering #DeveloperGrowth
Accessing DOM Elements in JavaScript: getElementById, getElementsByClassName, getElementsByTagName, querySelector, querySelectorAll
More Relevant Posts
-
Understanding JavaScript Events — Where Web Pages Become Interactive While learning JavaScript, one concept that really changed how I see web pages is Events. Before events, a webpage is just structure and styling. With events, it starts responding to users. 👉 That’s where interaction begins. ✅ What is a JavaScript Event? An event is an action that happens in the browser. For example: • A user clicks a button • Types in an input field • Moves the mouse • Submits a form • A page finishes loading JavaScript listens to these actions and responds accordingly. ✅ Common JavaScript Events • click → when a user clicks an element • input → when input value changes • submit → when a form is submitted • mouseover → when mouse moves over an element • load → when page finishes loading Example: button.addEventListener("click", function() { console.log("Button clicked"); }); ✅ Why Events Matter Events allow us to: • Create dynamic user interfaces • Validate inputs instantly • Trigger API calls • Improve user experience Without events, modern web applications wouldn’t exist. 💡 My learning takeaway: Coming from a backend background, events feel similar to handling requests — something happens, and logic responds to it. Understanding events made JavaScript feel much more practical and alive. What was the first JavaScript event you implemented when learning frontend? 👇 #JavaScript #FrontendDevelopment #WebDevelopment #DOM #WebEvents #LearningJourney #FullStackDeveloper #Programming #SoftwareEngineering #DeveloperGrowth
To view or add a comment, sign in
-
-
Hello everyone 👋 Welcome to Day 20 of my JavaScript learning journey 🚀 Today I built a Real-Time Digital Clock using HTML, CSS, and JavaScript, where the time updates every second automatically. This project helped me understand how JavaScript works with time, intervals, and continuous DOM updates. ⏰ Project: Digital Clock The clock: ✔ Displays the current time (HH:MM:SS) ✔ Updates automatically every second ✔ Uses a clean and minimal UI ✔ Runs continuously without page reload It feels simple on the surface, but it teaches an important real-world concept. 🔧 Concepts I Applied In this project, I worked with: 🔹 Date() object to get current time 🔹 toLocaleTimeString() for readable format 🔹 setInterval() to update time every second 🔹 DOM selection using getElementById() 🔹 Updating content dynamically with innerHTML This showed me how JavaScript can continuously update the UI in real time. 🧠 What I Learned • How real-time applications update data • How setInterval() works behind the scenes • How JavaScript handles time-based logic • How DOM updates can run continuously without user input This project made me more comfortable with timers and live data updates. 🎯 Day 20 Takeaway From handling user clicks to handling time itself, JavaScript keeps getting more powerful ⏳💻 Building small projects like this is helping me connect concepts and gain confidence with real-world frontend logic. Next ideas: 👉 Stopwatch / Timer 👉 Countdown Clock 👉 Date & Time Dashboard #javascript #webdevelopment #frontenddevelopment #learninginpublic #codingjourney #developers #100daysofcode #dom #projects #selflearning
To view or add a comment, sign in
-
-
🚀 Top 20 JavaScript Concepts Every Developer Must Master. 1️⃣ Hoisting JavaScript moves variable and function declarations to the top of their scope before execution. 2️⃣ Closures A function that remembers variables from its outer scope even after the outer function has finished. 3️⃣ Scope (Global, Function, Block) Determines where variables are accessible. 4️⃣ Lexical Scope Scope is decided by where functions are written, not where they are called. 5️⃣ Prototypes & Inheritance JavaScript uses prototypal inheritance to share properties and methods between objects. 6️⃣ Event Loop Handles asynchronous operations in JavaScript’s single-threaded environment. 7️⃣ Call Stack Tracks function execution order. 8️⃣ Async/Await Cleaner way to handle asynchronous code using promises. 9️⃣ Promises Represents a value that may be available now, later, or never. 🔟 Callback Functions Functions passed as arguments to other functions. 1️⃣1️⃣ Debounce & Throttle Improve performance by controlling how often functions run. 1️⃣2️⃣ Event Delegation Attach event listeners to parent elements instead of multiple children. 1️⃣3️⃣ Truthy & Falsy Values Understanding how JavaScript evaluates values in conditions. 1️⃣4️⃣ Type Coercion JavaScript automatically converts types (== vs === difference). 1️⃣5️⃣ Destructuring Extract values from arrays or objects easily. 1️⃣6️⃣ Spread & Rest Operators Expand arrays/objects or collect function arguments. 1️⃣7️⃣ ES6 Modules Organize and reuse code using import and export. 1️⃣8️⃣ Memory Management & Garbage Collection JavaScript automatically allocates and frees memory. 1️⃣9️⃣ IIFE (Immediately Invoked Function Expression) Function that runs immediately after it’s defined. 2️⃣0️⃣ The " this" Keyword 'this'refers to the object that is calling the function. Its value depends on how the function is invoked (not where it’s defined). In arrow functions, this is inherited from the surrounding scope. #JavaScript #FrontendDeveloper #BackendDeveloper #WebDevelopment #FullstackDeveloper #Developers
To view or add a comment, sign in
-
-
Hello everyone 👋 Welcome to Day 14 of my JavaScript journey 🚀 Today I went deeper into DOM Manipulation and learned how to create, delete, and modify elements dynamically using JavaScript. This is where webpages stop being static and start becoming interactive and dynamic 🌐 🧱 Creating & Adding Elements I practiced how to: • Create new elements using document.createElement() • Add text using innerText • Add classes using classList.add() • Insert elements into the page with appendChild() Now I can dynamically generate content instead of writing everything manually in HTML. ❌ Removing Elements I learned how to remove elements using: • .remove() (modern method) • Targeting elements like lastElementChild This showed me how UI elements can be controlled and updated in real time. 🎨 Modifying Styles & Classes Instead of only using inline styles, I learned the better approach: ✔ classList.add() ✔ classList.remove() ✔ classList.toggle() ✔ classList.contains() This is how real projects manage styling through CSS classes. 🏷 Working with Attributes I practiced: • setAttribute() and getAttribute() • Using dataset to store custom data inside elements This helped me understand how extra information can be attached to HTML elements. 🔤 Content Handling I also understood the difference between: • innerText • textContent • innerHTML This is important for controlling how text and HTML content are displayed. 🧪 Hands-On Practice To apply everything, I created a small HTML practice page and: • Dynamically added and removed elements • Changed styles using JavaScript (like document.body.style.backgroundColor ) • Toggled classes to change shapes and appearance • Tested attribute changes and data storage This practical work helped me understand how all these concepts come together in a real webpage. 🎯 Day 14 Takeaway Today made it clear how JavaScript controls the structure, style, and content of a webpage dynamically. From creating elements to modifying styles and attributes, I’m now building real interactive behavior using JavaScript 💻 Next step: DOM Events and user interaction 🚀 #javascript #dom #webdevelopment #frontenddevelopment #learninginpublic #codingjourney #developers #100daysofcode #selflearning #programming
To view or add a comment, sign in
-
Want to add or remove elements on your webpage using JavaScript? It’s easier than you think! Here is my go-to cheatsheet for DOM Manipulation. Creating a dynamic website means you need to know how to add, move, or delete elements on the go. If you are learning JavaScript, these DOM methods are your best friends! Here is a simple guide to managing elements like a pro: 1. Creating an Element : Before adding something to your page, you need to create it in memory. document.createElement('p'): This creates a new tag (like a paragraph, button, or heading). 2. Adding Elements to the Page : Once your element is ready, you need to "park" it somewhere on your webpage: appendChild(): Places the element as the last child of the parent. prepend(): Places the element at the very beginning (start) of the parent. append(): A modern way to add multiple elements or even plain text strings at once. 3. Precise Positioning (The "Swiss Army Knife") : If you need exact control, use insertAdjacentElement(position, element). It gives you 4 options: beforebegin: Before the element itself. afterbegin: Just inside, before the first child. beforeend: Just inside, after the last child. afterend: Right after the element. 4. Removing Elements : Cleaning up your code is just as important! removeChild(): Used when you want the parent to remove a specific child. remove(): A direct way to delete an element from the page completely. Pro Tip: While appendChild is classic, append() is much more flexible for modern projects as it handles both text and multiple nodes! #JavaScript #WebDevelopment #CodingTips #Frontend #Programming #BeginnerCoder #JSCheatSheet
To view or add a comment, sign in
-
🚀 JavaScript Learning Update – Day 22 Today, I learned how to modify text and content inside HTML elements using JavaScript. I explored: • textContent – to get or set all the text inside an element • innerText – to access only the visible text on the page • innerHTML – to read or update HTML content inside an element Understanding the difference between these methods helped me see how JavaScript can dynamically update web page content. This is an important step toward building interactive web applications where the UI changes based on user actions. Learning step by step and strengthening my DOM fundamentals. #JavaScript #DOM #WebDevelopment #FrontendDeveloper #LearningInPublic #CodingJourney
To view or add a comment, sign in
-
🥇Mastering JavaScript — One Concept at a Time (1/32) What are Variables & why var, let, const really matter. As part of my journey to master JavaScript, I decided to revisit the very basics starting with variables. And honestly, understanding this properly explains so many mistakes I made earlier. 📦What are variables? Variables are like containers that store data. They help us store, reuse, and update information from simple numbers to complex objects and arrays. Think of a variable as a box with a name on it: -The name is the variable identifier -The value is whatever data we put inside In JavaScript, we create these boxes using: 👉 var, let, and const 🧓 var — Old and risky 1️⃣Function scoped (not block scoped) 2️⃣Can be redeclared and reassigned 3️⃣Hoisted and initialised with undefined 🧑💻 let — Modern and safer 1️⃣Block scoped { } 2️⃣Can be reassigned, but not redeclared 3️⃣Hoisted, but stays in the Temporal Dead Zone (TDZ) 🔐 const — Predictable by default 1️⃣Must be assigned at declaration 2️⃣Cannot be reassigned or redeclared 3️⃣Block scoped 4️⃣Also affected by TDZ 🧠 Mindset Revisiting fundamentals is not about “going backwards”, it’s about building stronger foundations. My current approach: - Prefer const by default - Use let only when reassignment is necessary - Avoid var in modern JavaScript - Understanding why these rules exist makes the language feel far more predictable and reliable. 📌 Note: I intentionally didn’t go deep into HOISTING and the TDZ, I will break those down clearly in the next post in this series. This is just the beginning of my journey to master JavaScript — one concept at a time. 💬 How did you first understand the difference between var, let, and const? #JavaScript #LearningInPublic #WebDevelopment #FrontendDevelopment
To view or add a comment, sign in
-
Day 11: Callback Functions in JavaScript JavaScript is single-threaded… so how does it handle async tasks? 🤔 The answer starts with Callbacks. 🔹 What is a Callback? A callback function is a function that is: ✅ Passed as an argument to another function ✅ Executed later 🔹 Basic Example function greet(name) { console.log("Hello " + name); } function processUser(callback) { const name = "Shiv"; callback(name); } processUser(greet); Here, greet is a callback function. 🔹 Async Example setTimeout(function() { console.log("Executed after 2 seconds"); }, 2000); 👉 The function runs after a delay 👉 JavaScript does not block execution 🔥 Why Callbacks Are Important ✔️ Foundation of async JavaScript ✔️ Used in APIs, event listeners, timers ✔️ Core concept before learning Promises ⚠️ The Problem: Callback Hell When callbacks are nested too much: api1(function() { api2(function() { api3(function() { console.log("Done"); }); }); }); This leads to: ❌ Hard-to-read code ❌ Pyramid structure ❌ Difficult debugging This problem was later solved using Promises and Async/Await. #Javascript #CallBack #webdevelopment #LearnInPublic
To view or add a comment, sign in
-
👨💻Mastering JavaScript — One Concept at a Time (4/32) Operators are the verbs of your code. While revisiting JavaScript fundamentals, I noticed something interesting: 🔹 What Are Operators? Operators are symbols that tell JavaScript to perform an operation. They allow us to: Calculate values, compare data, make decisions, combine logic and modify variables. 1️⃣ Arithmetic Operators These are the most familiar ones used for mathematical operations. Addition, subtraction, multiplication, division, modulus, and exponentiation. But even here, JavaScript has quirks. For example, + is not just addition, but also performs string concatenation. That dual behaviour is something I now pay close attention to. 2️⃣ Comparison Operators These help us compare values; they return a boolean (true or false). Important distinction: Loose comparison (==) Strict comparison (===) Earlier in this series, I discussed why strict comparison is usually safer. Revisiting this again reinforces how small operator choices can prevent big bugs. 3️⃣ Logical Operators These are used for combining conditions: AND (&&), OR (||), NOT (!). What I appreciate now is that logical operators don’t just return true or false they return actual values based on truthy and falsy evaluation.That subtle behavior is powerful in real-world applications. 4️⃣ Unary Operators Unary operators work with a single operand. Examples include: Increment (++), Decrement (--), typeof, Logical NOT (!). They seem simple, but understanding how they affect state (especially in loops) matters a lot. ❓ Ternary Operator The ternary operator is JavaScript’s compact decision-maker. It’s a shorthand for if...else. Clean and readable when used properly. Confusing and messy when overused. I’ve learned that readability should always come before cleverness. 💡 Learning Mindset While revising this, I’m not just memorising operators. I’m asking: What exactly does this operator return? Does it mutate the value? Is it safe and readable? What operator confused you the most when you first learned JavaScript? #JavaScript #LearningInPublic #WebDevelopment #FrontendDevelopment #MasteringJavaScript
To view or add a comment, sign in
-
We're sleeping on the <dialog> element. 💡 After building countless modals with JavaScript libraries and CSS hacks, I finally gave the native HTML <dialog> element a serious try. My verdict: It's a game-changer that more developers should be using. Why <dialog> deserves your attention: -> Native accessibility - Built-in focus trapping, ESC closing, and screen reader support -> Simpler JavaScript - .showModal() and .close() vs managing z-index and event listeners -> Backdrop styling - Style the ::backdrop pseudo-element directly with CSS -> Lightweight - No dependencies, smaller bundle size The reality check: Browser support is now excellent (93% global). Polyfills exist for the rest. We're past the "waiting for support" phase. My prediction: In 2 years, <dialog> will be the standard way we build modals, with libraries becoming the exception rather than the rule. Am I crazy for thinking this? Have you used <dialog> in production? What's been your experience? 👇 #WebDevelopment #HTML #Frontend #JavaScript #Accessibility #WebStandards #Programming #WebDev #100Devs
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development