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.

asked Oct 27, 2015 at 11:34

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

answered Oct 27, 2015 at 11:42
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);
}
answered Oct 27, 2015 at 11:38

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?

XCS
28.3k28 gold badges105 silver badges155 bronze badges
answered Oct 27, 2015 at 11:37

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));
}
answered Oct 27, 2015 at 11:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.