Target class with javascript

event.target JavaScript

event.target returns the DOM element that triggered a specific event, so we can retrieve any property/ attribute with a value.

For example, when we console.log(e.target), we can see the element’s class name, type, the position of the mouse, etc.

const button = document.querySelector(".btn"); button.addEventListener("click", buttonClick); function buttonClick(e) < console.log(e.target); // 

Note: The difference between clientX, clientY and offsetX, offsetY

  • e.clientX: get the position on the x-axis when we click. It counts the position from the width of the browser window.
  • e.clientY: Similar to clientX, but get the position on the y-axis when we click.
  • e.offsetX and e.offsetY: get the position from the actual element.

II. event.target.value

We can access the value of an event with event.target.value.

Читайте также:  Установить python через командную строку linux

Example: We have a form, and we want to print out the value we type in.

III. Event type for text

In addition to keydown, we have other event types for text:

  • keyup
  • keypress
  • focus
  • blur
  • cut
  • paste
  • input: Event fires whenever we do anything with the input.

Источник

Target class with javascript

Last updated: Jan 11, 2023
Reading time · 2 min

banner

# Check if event.target has a specific Class using JavaScript

To check if event.target has a specific class, call the classList.contains() method on the target object.

The method returns a boolean result — true if the class is contained in the element’s class list and false otherwise.

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> style> .box background-color: salmon; height: 100px; width: 100px; margin: 10px; > style> head> body> div class="box box1">Box 1div> div class="box box2">Box 2div> div class="box box3">Box 3div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
document.addEventListener('click', function handleClick(event) const hasClass = event.target.classList.contains('box1'); console.log(hasClass); if (hasClass) console.log('Event.target has the specified class'); > else console.log('Event.target does NOT have the specified class'); > >);

We added a click event listener to the document object.

Every time we click on an element, a function is invoked.

We used the target property on the event object. The target property is a reference to the object (element) on which the event was dispatched.

The classList.contains method allows us to check if an element’s class list contains the provided class.

If the element has the class, the method returns true , otherwise false is returned.

Since the only element in the example that has the class of box1 is the first box, clicking on the element logs true to the console.

Clicking on any other element on the page logs false to the console.

# Check if event.target has a specific Class using matches()

You can also use the Element.matches method to check if event.target has a specific class.

Copied!
document.addEventListener('click', function handleClick(event) const hasClass = event.target.matches('.box1'); console.log(hasClass); if (hasClass) console.log('Event.target has the specified class'); > else console.log('Event.target does NOT have the specified class'); > >);

The code sample checks if event.target has a class of box1 .

The matches() method of the Element interface takes a selector and tests whether the element would be selected by the provided selector.

Notice that we passed a selector to the method ( .box1 ) instead of the name of the class.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Check if event.target has a Specific Class Using JavaScript

Sometimes, the programmer may want to check if the element that triggered the event (the event.target) matches the selector they care about. How to do this? JavaScript offers some predefined methods such as “contains()” and “matches()” methods to identify the specific selector in a target event.

This post will explain the methods to determine whether the event.target has a particular class or not using JavaScript.

How to Check if event.target has a Specific Class Using JavaScript?

To determine if the event.target has a particular class, use the following JavaScript predefined methods:

Let’s see how these methods work for determining class in an event.target.

Method 1: Check if event.target has a Specific Class Using contains() Method

To determine whether an element belongs to a specific class, use the “contains()” method of the “classList” object. The contains() method is used to identify whether a specified item is present in the collection. Its outputs “true” if the item is present, else, it gives “false”. It is the most efficient way for determining an element’s class.

Follow the below-given syntax to determine whether the event.target has a specific class or not using the contains() method:

  • event.target” is a triggered event that will be checked whether it contains the specific class or not.
  • The “class-name” identifies the name of the CSS class that is a part of the triggered event.

Return value

It returns “true” if the triggered event has the specified class; otherwise, it returns “false”.

Example

First, create three “div” elements in an HTML file using the HTML tag:

Style the elements using CSS styling. To do so, create a CSS class “.div” for all the div elements:

Create a “.center” class for setting the elements in the center of the page:

Now, for styling, every div individually creates a CSS class for them. For the first div, set the background color “red” in the “div1Style” class:

For the second div, set the background color “radish pink” using the “rgba(194, 54, 77)” code in the “div2Style” class:

background — color : rgb ( 194 , 54 , 77 ) ;

Set the background color “pink” of the third div by creating the “div3Style” class:

After running the above HTML code, the output will look like this:

Now, in a JavaScript file or a “script” tag, use the below-provided code to check whether the event.target has a specific class or not:

document. addEventListener ( ‘click’ , function handleClick ( event ) {

var hasClass = event. target . classList . contains ( ‘center’ ) ;

alert ( «This div contains ‘center’ class: » + hasClass ) ;

In the above code snippet:

  • First, attach an event listener on a click event that will handle every click on DOM.
  • Then, check whether the triggered event has the CSS class “center” or not with the help of the “classList.class()” method.

The above GIF shows that div1 contains the “center” class as it shows “true”, while div2 and div3 display “false” in the alert box, which means they do not contain the “center” class.

Method 2: Check if event.target has a Specific Class Using matches() Method

Another JavaScript predefined method called “matches()” can be used to check whether a specific class belongs to an element or an event. The “class-name” is the only parameter needed to determine whether an element or a target event includes a certain class or not.

The below-given syntax is utilized for the matches() method:

  • event.target” is a triggered event that will be checked whether it contains the specific class or not.
  • The “class-name” indicates the name of the CSS class that is a part of the triggered event. The matches() method takes the class’s name together with a dot (.) that denotes the word “class”.

Return value

If the target event has a class, it returns “true” else, “false” is returned.

Example

In a JavaScript file or a script tag, use the below lines of code to check whether the event.target has a specific class or not by using the “matches()” method:

document. addEventListener ( ‘click’ , function handleClick ( event ) {

var hasClass = event. target . matches ( ‘.div3Style’ ) ;

alert ( «This div’s class matches the ‘div3Style’ class: » + hasClass ) ;

In the above lines of code:

  • First, attach an event listener on a click event that will handle every click on DOM.
  • Then, check whether the “div3Style” CSS class exists in a triggered event using the “matches()” method.
  • If it is present, the alert() shows a message with “true”, else “false”.

The above GIF shows that only div3 contains the “div3Style” class as it shows “true”.

Conclusion

To determine whether a triggered event has a specified class, use the JavaScript “contains()” method or the “matches()” method. However, the contains() method is one of the most useful approaches used to determine an element’s class. Both methods return “true” if the triggered event has a class else “false” is returned. This post explained the methods to determine whether the event.target has a particular class or not using JavaScript.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

Target class with javascript

You can pass as many classes to the add() method as necessary.

Copied!
document.addEventListener('click', function handleClick(event) event.target.classList.add( 'bg-yellow', 'second-class', 'third-class' ); >);

If any of the classes are already present on the element, they won’t get added a second time.

Similarly, if you need to remove one or more classes, you can use the remove() method.

Copied!
document.addEventListener('click', function handleClick(event) event.target.classList.add( 'bg-yellow', 'second-class', 'third-class' ); event.target.classList.remove( 'second-class', 'third-class' ); >);

If any of the classes are not present on the element, they get ignored.

# Add class to selected Elements on click

To add a class to selected elements on click:

  1. Select a group of elements using the document.querySelectorAll() method.
  2. Use a for. of loop to iterate over the collection.
  3. On each iteration, add a click event listener to the element that adds a specific class.

Here is the HTML for this example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> style> .bg-yellow background-color: yellow; > style> head> body> div class="box1">Box 1div> div class="box2">Box 2div> div class="box3">Box 3div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const boxes = document.querySelectorAll('.box1, .box2, .box3'); for (const box of boxes) box.addEventListener('click', function handleClick() box.classList.add('bg-yellow'); >); >

We used the document.querySelectorAll method to select the DOM elements with classes box1 , box2 and box3 .

We used the for. of loop to iterate over the collection of elements and added a click event handler to each element.

We used the add() method to add a class to the clicked element.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью