π 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);
}
π Global Variables:
- Declared outside all functions.
- Can be accessed anywhere in the script.
let globalVar = "I'm global";
function showGlobal() {
console.log(globalVar);
}
π§Ύ 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");
π Update:
You can change content or attributes like:
element.innerText = "New Text";
element.setAttribute("class", "newClass");
βοΈ 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:
- Create a
.js
file (e.g.,script.js
) - Link it in your HTML using:
<script src="script.js"></script>
π 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>
let para = document.getElementById("demo");
console.log(para.innerText); // Output: Hello
π² 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)