Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding class to clicked element

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>
like image 551
Kim Avatar asked May 15 '13 21:05

Kim


People also ask

How do I add a class to an element in HTML?

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so: document. getElementById("MyElement").

How do I add a class to an element in CSS?

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.

How do you add a class to a script?

add() method: This method is used to add a class name to the selected element. Syntax: element. classList.


1 Answers

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") { ... }
  ... 
like image 77
steo Avatar answered Sep 21 '22 22:09

steo