简体   繁体   中英

How to use querySelector with an anchor tag with href?

I'm trying to use dropzone and I have a anchor tag and I need to add a event click to it but the way I'm done this returns error.

Html:

<a href="#new-intervention">Criar Intervenção</a>

Jquery:

var myDropzone = this;

this.element.querySelector("a[href=#new-intervention]").addEventListener("click", function(e) {
  e.preventDefault();
  e.stopPropagation();
  myDropzone.processQueue();
 });

And return me this in console:

Uncaught DOMException: Failed to execute 'querySelector' on 'Element': 'a[href=#new-intervention]' is not a valid selector.

How can I do that? What is the alternative?

The error message already gives it away. The selector should be a[href='#new-intervention'] . Notice the single quotes around the value of href .

Here is a simplified snippet to show the selector working:

 console.log(document.querySelector("a[href='#new-intervention']"));
 <a href="#new-intervention">Criar Intervenção</a>

Note that according to the spec , the value provided must either be a valid identifier or a string .

You just the missed the quotes ' inside the href value query selector expression ;

see below snippet :

 document.querySelector("a[href='#new-intervention']").addEventListener("click", function(e) { e.preventDefault(); e.stopPropagation(); alert("a clicked"); });
 <a href="#new-intervention">Criar Intervenção</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM