1

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.

4 Answers 4

1
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

Sign up to request clarification or add additional context in comments.

Comments

1
//Check there if it's an html tag: 

if (eType == "div"){

document.createElement(eType);

}

1 Comment

This is good but however you'll need || for every tag. In my answer it's just adding a new value to the array. Not saying your way is wrong, it can be better.
1
var validTags = ['div'];
function is_tag(tag) {
    return validTags.indexOf(tag.trim().toLowerCase()) > -1;
}

Something like this?

Comments

0

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));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.