querySelector
Lesson 8 of 13 in Coddy's JavaScript DOM Methods course.
The function querySelector() selects the first element that matches a powerful CSS-like selector, providing more flexibility than the previous methods for complex element selection. Example:
const button = document.querySelector("#btn");This is how we access the button element with btn id.
Challenge
EasyYou are given HTML code that contains a button.
Using JavaScript only,
- Retrieve the element using
querySelectorfunction. - Change
backgroundColorto red usingstyleproperty. - Change
colorto white usingstyleproperty.
Try it yourself
<!DOCTYPE html>
<html>
<body>
<button id="myButton">Click Me</button>
<script src="script.js"></script>
</body>
</html>All lessons in JavaScript DOM Methods
2DOM Methods I
getElementByIdModify Element StylegetElementsByClassNameLoop Through and ManipulategetElementsByTagNamequerySelector