I'm trying to add a class to a clicked element. There are multiple elements with unique IDs so I "don't know" what the ID of the element is.
Can I use a modified version of the below code to achieve this?
Jquery:
$(document).ready(function () {
$(this).on('click', function () {
$(this).addClass('widget-selected');
});
});
EDIT:
A markup can be like this:
<h1 id="textHolder1" contenteditable="true">Text to edit</h1>
To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so: document. getElementById("MyElement").
If you want to use a class, use a full stop (.) followed by the class name in a style block. Next, use a bracket called a declaration block that contains the property to stylize the element, such as text color or text size. CSS Classes will help you stylize HTML elements quickly.
add() method: This method is used to add a class name to the selected element. Syntax: element. classList.
I would try with this..
$(document).ready(function () {
//this will attach the class to every target
$(document).on('click', function (event) {
$target = $(event.target);
$target.addClass('widget-selected');
});
})
or if you want to check a certain id
use
...
if(event.target.id === "idname") { ... }
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With