1

Good Morning,

I'm currently looking for a solution to get the DOM element id on two occasions.

  • Occasion one: When the mouse enters a div get the ID of the div its entered.
  • Occasion two: When the mouse leaves a div get the ID of the div it left.

It's dynamic content therefore I have the following base code:

$(document).on({
    mouseenter: function(e) {

    },
    mouseleave: function(e) {

    }
}, '.template-builder-template-stream-slot');

However, I'm having problems getting the actual id of the element on the above two occasions.

Thanks for your help!

Joshua
  • 588
  • 1
  • 5
  • 19

4 Answers4

3

You can simply use this.id, assuming your .template-builder-template-stream-slot element actually has an ID when this code is fired. If it doesn't have an ID, the result will be blank.

$(document).on({
    mouseenter: function(e) {
      console.log("mouseenter on #" + this.id);
    },
    mouseleave: function(e) {
      console.log("mouseleave on #" + this.id);
    }
}, '.example');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<figure class="example" id="one">This has an ID of "one".</figure>
<figure class="example" id="two">This has an ID of "two".</figure>
<figure class="example">This has no ID at all.</figure>

If we move our cursor over both of these from top to bottom, we'll get the following result in our JavaScript console (note how the last element, which has no ID, returns no value (an empty string)):

Console Log

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
1

You may use this or e.target.id. For more you may visit Getting the ID of the element that fired an event

Community
  • 1
  • 1
pTM
  • 21
  • 2
0

Both this and e.target refer to the target element:

var id = e.target.id;
var id = this.id;

If this value is an empty String, the target element does not have an id attribute.

You could verify that this is the case by logging the target elements:

$(document).on({
    mouseenter: function(e) {
        console.log(this); // logs a DOM element
        console.log(this.id); // logs the id if present, or blank otherwise.
    }
}, '.template-builder-template-stream-slot');
joews
  • 29,767
  • 10
  • 79
  • 91
0

You may use "e.target.id" for accessing id of the elements inside mouseenter and mouseleave method.

Paritosh
  • 505
  • 5
  • 13