检查作为函数参数输入的字符串是否是 HTML 标记名之一



我正在研究一个可以使用的构造函数,如以下代码中显示的代码注释中所述:

//CONSTRUCTOR
//creates a child element of the specified kind
//adds the child to specified parent
//optionally assigns the child an ID
// optionally assigns the child up to 4 classes
function Adjoin(childKind = undefined, childID = undefined, firstChildClass = undefined, secondChildClass = undefined, thirdChildClass = undefined, fourthChildClass = undefined) {
if (!(this instanceof Adjoin)) {
return new Adjoin(childKind = undefined, childID = undefined, firstChildClass = undefined, secondChildClass = undefined, thirdChildClass = undefined, fourthChildClass = undefined);
}
this.childKind = childKind;
this.childID = childID;
this.firstChildClass = firstChildClass;
this.secondChildClass = secondChildClass;
this.thirdChildClass = thirdChildClass;
this.addChildTo = function(parentID) {
const parent = document.getElementById(parentID);
const child = document.createElement(childKind);
parent.appendChild(child);
if (childID !== undefined) {
child.setAttribute("id", childID);
}
if (firstChildClass !== undefined) {
child.classList.add(firstChildClass);
}
if (secondChildClass !== undefined) {
child.classList.add(secondChildClass);
}
if (thirdChildClass !== undefined) {
child.classList.add(thirdChildClass);
}
if (fourthChildClass !== undefined) {
child.classList.add(fourthChildClass);
}
}
};

如果我在某处输入这样的代码,这将起作用:

new Adjoin("div", "foo_id", "foo_class").addChildTo("some_parent")

这也很好用:

new Adjoin("div").addChildTo("some_parent")

我坚持的是一种检查第一个参数是否是 HTML 标签名称之一的方法。 例如,如果输入代码为:

new Adjoin("not_an_html_element", "foo_id", "foo_class").addChildTo("manchoo_parent")

提前感谢!

更新

好吧,看来我发布这个问题有点太快了! 我输入了以下代码:

new Adjoin(75).addChildTo("footer");

并得到此错误:

未捕获的 DOMException:无法在"文档"上执行"createElement":提供的标记名称 ("75"( 不是有效名称。

所以已经有一个内置的错误。

但是,当我输入以下代码时:

new Adjoin("DaveyJones").addChildTo("footer");

我在网站的页脚中添加了以下"标签":

<daveyjones></daveyjones>

显然,这不是一个有效的 HTML 标记。

对于不是字符串的任何内容,都会引发错误,但任何字符串都将添加 HTML 标记而不会出现错误。

又一次更新

我按照user2676208的建议尝试了这个,并在这个问题中将其设置为条件:

if (document.createElement(this.childKind).toString() != "[HTMLUnknownElement]") {
console.log("That is a valid HTML element!")
} else {
console.log("That is NOT a valid HTML element!")
}

但是,它总是记录"这是一个有效的HTML元素!",无论我使用"div"还是"DaveyJones"还是"anyOtherString"。

尽管我不喜欢这个想法,但我可能不得不通过设置标签名称数组并在循环中进行比较来做到这一点。 我只是真的希望有一种方法可以避免这种情况,因为这对我来说似乎很笨拙。 我预计Javascript已经有了一种检查有效HTML的方法......

我认为我不能将其标记为重复项,但您应该在此处查看问题:验证字符串是否为有效的 HTML 标记名称。

从斯特里纳的回答来看,

function isValid(input) {
return document.createElement(input).toString() != "[object HTMLUnknownElement]";
}

不会引发错误,因为即使您创建的元素不是有效的 HTML 标记,它仍将创建该元素,但它将是一个 HTMLUnknownElement。
因此,为什么仍然显示<daveyjones></daveyjones>

为了解决您的问题,您应该有一个函数来验证您收到的输入是否是有效的 HTML 标记

您可以创建一个您希望被视为有效的 HTML 标记数组,并使用 Array.indexOf(( 检查在函数中创建的元素是否存在于此数组中。

最新更新