js querySelectorAll not a valid selector despite it being like the docs example [duplicate]

天涯浪子 提交于 2021-02-05 09:15:06

问题


https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Here, an attribute selector is used to return a list of the list items contained within a list whose ID is "userlist" which have a "data-active" attribute whose value is "1"

var container = document.querySelector("#userlist");
var matches = container.querySelectorAll("li[data-active=1]");

but when i try

var matches = document.querySelectorAll('div[data-id=7821549]');

i get:

DOMException: Failed to execute 'querySelectorAll' on 'Document': 'div[data-id=7821549]' is not a valid selector.

this is the div im trying to get:

<div class="cell cell--event-list cell--odds js-event js-event-odds js-event-odds-7821549 js-event-status-finished" data-id="7821549">

回答1:


The example selector "li[data-active=1]" throws a similar error on my Chromium browser as the attribute selector value is a number. Even simple numeric ID selectors (like #22) for valid HTML5 IDs do not work with querySelector method.

Wrapping the attribute selector's value with quotes solves the issue: 'div[data-id="7821549"]'



来源:https://stackoverflow.com/questions/52673617/js-queryselectorall-not-a-valid-selector-despite-it-being-like-the-docs-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!