我想通过 document.querySelectorAll
获取浏览器(和 JSDOM)未知的所有元素.
我试过使用 .toString
然后检查元素是否注册为 HTMLUnknownElement
像这样:
if (node.toString() === "[object HTMLUnknownElement]") ...
但是如果有问题的元素有 -
,这就不起作用了在其名称中,例如 <test-element>
.我假设与 HTML 自定义元素兼容。现在,我只是列出了负载为 :not
的所有元素。用于我所知道的每个标签,但这感觉像是一个 hack:
document.querySelectorAll("*:not(html):not(head):not(link):not(meta):not(base):not(script):not(style):not(title):not(body):not(address):not(article):not(aside):not(footer):not(h1):not(h2):not(h3):not(h4):not(h5):not(h6):not(header):not(hgroup):not(nav):not(section):not(blockquote):not(cite):not(dd):not(dl):not(div):not(dt):not(figcaption):not(figure):not(hr):not(li):not(ol):not(ul):not(menu):not(main):not(p):not(pre):not(a):not(abbr):not(b):not(bdi):not(bdo):not(br):not(code):not(data):not(time):not(dfn):not(em):not(i):not(kbd):not(mark):not(q):not(rp):not(ruby):not(rt):not(rtc):not(rb):not(s):not(del):not(ins):not(samp):not(small):not(span):not(strong):not(sub):not(sup):not(u):not(var):not(wbr):not(area):not(map):not(audio):not(source):not(img):not(track):not(video):not(embed):not(object):not(param):not(picture):not(canvas):not(noscript):not(caption):not(table):not(col):not(colgroup):not(tbody):not(tr):not(td):not(tfoot):not(th):not(thead):not(button):not(datalist):not(option):not(fieldset):not(label):not(form):not(input):not(legend):not(meter):not(optgroup):not(select):not(output):not(progress):not(textarea):not(details):not(dialog):not(menuitem):not(summary):not(content):not(slot):not(element):not(shadow):not(template):not(acronym):not(applet):not(basefont):not(font):not(big):not(blink):not(center):not(command):not(dir):not(frame):not(frameset):not(image):not(isindex):not(keygen):not(listing):not(marquee):not(multicol):not(nextid):not(noembed):not(plaintext):not(spacer):not(strike):not(tt):not(xmp)")
有人知道更好的方法吗?
最佳答案
其他答案没有为我的应用程序正确找到自定义元素。
我更改了代码片段,以下对我有用
function isUnknownElement(element) {
const tagName = element.tagName
if (tagName.includes('-')) {
return element.constructor.name === 'HTMLUnknownElement' ||
element.constructor.name === 'HTMLElement'
}
return element.constructor.name === 'HTMLUnknownElement';
}
function identifyUnknownElements(selector) {
const elements = document.querySelectorAll(selector);
const unknownElements = [];
for (let i = 0, length = elements.length; i < length; i++) {
if (isUnknownElement(elements[i])) {
elements[i].classList.add('unknown-element');
unknownElements.push(elements[i]);
}
}
return unknownElements;
}
console.log(identifyUnknownElements('*'))
关于javascript - 通过 document.querySelectorAll 获取未知元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47202147/