Check if HTML snippet is valid with Javascript

前端 未结 7 1962
忘了有多久
忘了有多久 2020-11-29 05:03

I need a reliable Javascript library / function to check if a HTML snippet is valid that I can call from my code. For example, it should check that opened tags and quotation

7条回答
  •  一整个雨季
    2020-11-29 05:55

    Using pure JavaScript you may check if an element exists using the following function:

    if (typeof(element) != 'undefined' && element != null)
    

    Using the following code we can test this in action:

    HTML:

    
    
    

    CSS:

    p:after {
        content: "Is 'undefined'";
        color: blue;
    }
    p.not-undefined:after {
        content: "Is not 'undefined'";
        color: red;
    }
    

    JavaScript:

    function checkNotUndefined(){
        var phrase = "not ";
        var element = document.querySelector('.not-undefined');
        if (typeof(element) != 'undefined' && element != null) phrase = "";
        alert("Element of class '.not-undefined' does "+phrase+"exist!");
        // $(".thisClass").length checks to see if our elem exists in jQuery
    }
    
    function toggleNotUndefined(){
        document.querySelector('p').classList.toggle('not-undefined');
    }
    

    It can be found on JSFiddle.

提交回复
热议问题