gpt4 book ai didi

javascript - 如何检测html中的非官方标签?

转载 作者:太空狗 更新时间:2023-10-29 13:27:00 25 4
gpt4 key购买 nike

给定一个 HTML 节点,你如何判断它是否带有官方 HTML 标签?

<h9 id="someNodeId">hello<h9>
let node = document.getElementById("someNodeId");

在上面的代码片段中,我希望 h9 不是官方的 html 标签。我如何使用 JS 以编程方式找到它?

编辑:最好在 O(1)

最佳答案

有人已经为此编写了一个很好的函数,参见 usage guide on GitHub .

例子:

isElementSupported("h1"); // true
isElementSupported("h9"); // false

/*
* isElementSupported
* Feature test HTML element support
* @param {String} tag
* @return {Boolean|Undefined}
*/

(function(win){
'use strict';

var toString = {}.toString;

win.isElementSupported = function isElementSupported(tag) {
// Return undefined if `HTMLUnknownElement` interface
// doesn't exist
if (!win.HTMLUnknownElement) {
return undefined;
}
// Create a test element for the tag
var element = document.createElement(tag);
// Check for support of custom elements registered via
// `document.registerElement`
if (tag.indexOf('-') > -1) {
// Registered elements have their own constructor, while unregistered
// ones use the `HTMLElement` or `HTMLUnknownElement` (if invalid name)
// constructor (http://stackoverflow.com/a/28210364/1070244)
return (
element.constructor !== window.HTMLUnknownElement &&
element.constructor !== window.HTMLElement
);
}
// Obtain the element's internal [[Class]] property, if it doesn't
// match the `HTMLUnknownElement` interface than it must be supported
return toString.call(element) !== '[object HTMLUnknownElement]';
};

})(this);
Tag: <input id="toCheck" type="text" value="h9"><br><br>
Is supported? <input id="result" type="text" readonly><br><br>
<input type="submit" value="Check Tag" onclick="document.getElementById('result').value= (isElementSupported(document.getElementById('toCheck').value))">

关于javascript - 如何检测html中的非官方标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53981083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com