DEV Community

A Ramesh
A Ramesh

Posted on

Day-12 : πŸ“ My JavaScript Learning Journey – Day 2 🌐 What I Learned Today: JavaScript Variables, DOM, and More!....

🌐 What I Learned Today: JavaScript Variables, DOM, and More!

Today was a great day of learning in my JavaScript journey! I covered some important theoretical concepts and practical basics that are essential for working with HTML and JavaScript together. Here’s a quick summary of what I learned:


🧠 1. JavaScript Variable Types: Local and Global

Understanding how variables work is very important in any programming language.

βœ… Local Variables:

  • Declared inside a function.
  • Can only be accessed within that function.
  • Good for temporary use or function-specific logic.
function myFunction() {
  let localVar = "I'm local";
  console.log(localVar);
}
Enter fullscreen mode Exit fullscreen mode

🌍 Global Variables:

  • Declared outside all functions.
  • Can be accessed anywhere in the script.
let globalVar = "I'm global";
function showGlobal() {
  console.log(globalVar);
}
Enter fullscreen mode Exit fullscreen mode

🧾 2. DOM Elements: Select, Create, Update, Rename

DOM stands for Document Object Model. It allows JavaScript to interact with the HTML content.

🟒 Select:

You can select HTML elements using:

  • getElementById()
  • getElementsByClassName()
  • getElementsByTagName()
  • querySelector() / querySelectorAll()[TBD]

βž• Create:

You can create new elements using:

let newDiv = document.createElement("div");
Enter fullscreen mode Exit fullscreen mode

πŸ” Update:

You can change content or attributes like:

element.innerText = "New Text";
element.setAttribute("class", "newClass");
Enter fullscreen mode Exit fullscreen mode

✏️ Rename (Not exactly rename, but change tag’s content or attributes):

You can't rename a tag directly, but you can replace it or update its name in a string and recreate it if needed.


πŸ”— 3. Linking External JavaScript File to HTML

To keep things organized, we write JavaScript in separate .js files.

Steps to Link:

  1. Create a .js file (e.g., script.js)
  2. Link it in your HTML using:
<script src="script.js"></script>
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Tip: Place the <script> tag just before the closing </body> tag so that HTML loads first.


πŸ” 4. Selecting Tags in HTML Using JavaScript

You can target HTML elements and work with them easily. For example:

<p id="demo">Hello</p>
Enter fullscreen mode Exit fullscreen mode
let para = document.getElementById("demo");
console.log(para.innerText);  // Output: Hello
Enter fullscreen mode Exit fullscreen mode

🌲 5. Understanding the DOM Model [TBD]

The DOM is like a tree structure where each HTML element is a node. JavaScript lets you:

  • Traverse the tree (parent, child, siblings)
  • Manipulate nodes (add, remove, change content)
  • React to events (clicks, typing, etc.)

Top comments (0)