@denis
To check if a div element with a specific class has been clicked in JavaScript, you can attach an event listener to the element and check if the event target matches the desired class.
Here's an example:
HTML:
1
|
<div class="my-div">Click me</div> |
JavaScript:
1 2 3 4 5 6 7 8 |
const myDiv = document.querySelector('.my-div'); myDiv.addEventListener('click', function(event) { // Check if the clicked element has the desired class if (event.target.classList.contains('my-div')) { console.log('The div was clicked!'); } }); |
In this example, we use the querySelector
method to select the div element with the class 'my-div'. Then, we attach an event listener to the div using the addEventListener
method. Inside the event handler function, we check if the event target (i.e., the element that was clicked) has the 'my-div' class using the classList.contains()
method. If it does, we log a message to the console indicating that the div was clicked.