1
What are Javascript Selectors?**
2
Javascript selectors are used to access the DOM (Document Object Model) to interact with and modify webpages in real-time. They allow developers to search for, retrieve, and manipulate HTML elements.
3
Common Javascript Selector Methods:**
4
`document.getElementsByTagName('div')`: Selects all elements with a specified tag name (e.g., all `<div>` elements).
5
`document.getElementsByClassName('done')`: Selects all elements that have a specific class name (e.g., elements with the class `done`).
6
`document.getElementById('my-id')`: Selects a single element by its unique ID (e.g., the element with `id="my-id"`).
7
`document.querySelector('#my-id')`: Selects the *first* element that matches a specified CSS selector (e.g., `#my-id` for an ID, `.classname` for a class, `div` for a tag).
8
`document.querySelectorAll('.classname')`: Selects *all* elements that match a specified CSS selector (e.g., all elements with the class `classname`).
9
Modifying Selected HTML Elements:**
10
Once an HTML element is selected, its properties can be modified:
11
Changing Inner HTML Content:** Use the `innerHTML` property to set or get the HTML content within an element.
12
Example: `document.getElementById('my-id').innerHTML = "new html"`
13
Changing Class Names:** Use the `className` property to set or replace the class attributes of an element.
14
Example: `document.getElementById('my-id').className = "newclass otherclass"`
15
Key Takeaway:** Javascript selectors are fundamental for dynamic web development, enabling beginners to make powerful changes to web pages by directly manipulating the DOM.