最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use querySelector with an anchor tag with href? - Stack Overflow

programmeradmin5浏览0评论

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?

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?

Share Improve this question edited Nov 13, 2019 at 2:35 Let Me Tink About It 16.1k21 gold badges108 silver badges217 bronze badges asked Jan 13, 2018 at 11:16 user3242861user3242861 1,92912 gold badges53 silver badges97 bronze badges 1
  • 2 Wrap the href value in single quotes ... – C3roe Commented Jan 13, 2018 at 11:17
Add a ment  | 

2 Answers 2

Reset to default 11

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>

发布评论

评论列表(0)

  1. 暂无评论