1

in jquery, I can easily create a event using attributes. here is the sample code.

$('body').on('mouseenter', '[email]', function(){})

My html tag is something like this.

<span class="zF" email="internal@xyz.com" name="internal">internal</span>

But I don't find any solution how can I do it using javascript.

does anyone know how to add event listener for an attribute using javascript?

Ketan Modi
  • 1,780
  • 1
  • 16
  • 28
  • Vanilla JS selectors can select elements with attributes just fine. Eg `target.closest('[email], a[href^="mailto:"]')` will give you an ancestor of the target which matches at least one of those attributes – CertainPerformance Dec 13 '19 at 06:57

1 Answers1

2

Use querySelector():

document.querySelector('[email]').addEventListener('mouseenter', doFunction);

document.querySelector(' a[href^="mailto:"]').addEventListener('mouseenter', doFunction);

function doFunction() {
  console.log('hover');
}
<span email="someEmail"> Hover to email </span>
<a href="mailto:somemail@gmail.com"> Hover to href </a>

Using querySelectorAll()

var elem = document.querySelectorAll('[email], a[href^="mailto:"]');
for(var i=0; i<elem.length; i++) {
  elem[i].addEventListener('mouseenter', doFunction);
}

function doFunction() {
  console.log(this.innerHTML);
}
<span email="someEmail"> Hover to email </span>
<a href="mailto:somemail@gmail.com"> Hover to href </a>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62