Objective:
Create and use a custom function to select DOM elements similar to how jQuery's $ function works.
Explanation:
We'll define a function named $ that uses document.querySelector to select an element based on a CSS selector.
Code Example:
Here's the HTML and JavaScript needed to create and use the custom $ function.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>DOM Selection Example</title>
</head>
<body>
<button id="submit-btn">Submit</button>
<div class="card">Card Content</div>
<input type="text" class="form" placeholder="Enter text">
<div class="space">Space Content</div>
<script src="script.js"></script>
</body>
</html>
JavaScript (script.js):
// Define the custom $ function
function $(selector) {
return document.querySelector(selector);
}
// Select elements using the custom $ function
const submitBtn = $('#submit-btn'),
card = $('.card'),
formInput = $('.form'),
space = $('.space');
// Log the selected elements to the console
console.log(submitBtn); // Output: <button id="submit-btn">Submit</button>
console.log(card); // Output: <div class="card">Card Content</div>
console.log(formInput); // Output: <input type="text" class="form" placeholder="Enter text">
console.log(space); // Output: <div class="space">Space Content</div>
Steps:
1. Define the Custom Function:
Create a function named $ that takes a selector as a parameter.
Use document.querySelector inside the function to return the selected element.
function $(selector) {
return document.querySelector(selector);
}
2. Select Elements:
Use the $ function to select elements from the DOM.
Pass a CSS selector (e.g., '#submit-btn', '.card') as the argument to the $ function.
const submitBtn = $('#submit-btn'),
card = $('.card'),
formInput = $('.form'),
space = $('.space');
3. Log the Selected Elements:
Log the selected elements to the console to verify that they have been correctly selected.
console.log(submitBtn); // Output: <button id="submit-btn">Submit</button>
console.log(card); // Output: <div class="card">Card Content</div>
console.log(formInput); // Output: <input type="text" class="form" placeholder="Enter text">
console.log(space); // Output: <div class="space">Space Content</div>
By defining a custom $ function, you can simplify the process of selecting DOM elements, making your code cleaner and more readable. This approach is especially useful if you are familiar with jQuery and want similar functionality in vanilla JavaScript.
Top comments (0)