Verify whether a string is a valid HTML tag name

后端 未结 3 944
小蘑菇
小蘑菇 2021-01-21 21:22

How can I find out if a string is a valid HTML tag?

For example: a, or h1, div, or span, ... are a valid HTML tagname. But ar, or abc, or div2, ... are invaild.

相关标签:
3条回答
  • 2021-01-21 22:02

    You will have to get and use your own array of HTML tags to check this - I would personally go with W3C spec instead of the w3schools one.

    Then, you want to use indexOf on the array and check if it's not -1, something like this:

    var isValid = function (tagCandidate) { return (validHtmlTags.indexOf(tagCandidate) > -1); };

    0 讨论(0)
  • 2021-01-21 22:03

    Get a list of valid HTML tags (or whatever you want to compare with) and simply do something like:

    function IsValid(s) {
        var tags = ['a', 'p', 'etc...'];
        return tags.indexOf(s) != -1;
    }
    
    0 讨论(0)
  • 2021-01-21 22:04

    HTML5 introduced the HTMLUnknownElement interface which must be used for elements that are not defined by the standard HTML specifications.

    When using document.createElement, if the element is not a valid tag by specification, it will be an object of type HTMLUnknownElement. Since using .toString will return [object type], you can create the element and test for that type:

    function isValid(input) {
      return document.createElement(input).toString() != "[object HTMLUnknownElement]";
    }
    
    console.log( isValid("tr") );
    console.log( isValid("a") );
    console.log( isValid("trs") );
    console.log( isValid("strong") );
    console.log( isValid("strongg") );

    However, this many not work in older browsers.

    0 讨论(0)
提交回复
热议问题