Am creating elements dynamically using
var eType = "div";
document.createElement(eType);
is there anyway to validate the provided string is an equivalent html tag.
if i provide something like var eType = "idv";
it has to send an error.
Any workarounds to check that.
var validTags = ['div'];
function is_tag(tag) {
return validTags.indexOf(tag.trim().toLowerCase()) > -1;
}
Something like this?
//Check there if it's an html tag:
if (eType == "div"){
document.createElement(eType);
}
function isValid(input) {
return document.createElement(input).toString() != "[object HTMLUnknownElement]";
}
alert(isValid("div"));
Not enough rep to flag, but duplication source: Verify whether a string is a valid HTML tag name
You can write a function to have included all valid tagNames and then see if [object HTMLUnknownElement]
function isValidHTMLTag(tagName, allowObsolete) { // use `-1` as second parameter to completely bypass allowObsolete check
var obsolete = ['acronym', 'applet', 'basefont', 'bgsound', 'big', 'blink', 'center', 'dir', 'font', 'frame', 'frameset', 'hgroup', 'isindex', 'listing', 'marquee', 'multicol', 'nextid', 'nobr', 'noembed', 'noframes', 'plaintext', 'spacer', 'strike', 'tt', 'xmp'];
return tagName.match(/[^a-zA-Z0-9]/) ? !1 : -1 !== allowObsolete && -1 !== obsolete.indexOf(tagName) ? allowObsolete || !1 : "[object HTMLUnknownElement]" !== Object.prototype.toString.call(document.createElement(tagName));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.