Search code examples
javascripthtmljquerylaravelcodemirror

JS search a string or html tag inside a string even if the searched term is not joined together


I have a code editor on my site, and after the user runs the code, I want to validate if the code is correct.

For example, if the user writes the following code:

<p>Some text</p>

I want to validate if the code contains a <p> tag.

What I tried :

if(language == "HTML"){
    if (html_code.includes(expected)) {
        alert('right!');
    }
    else {
       alert("wrong");
    }
} 

But it only works if the user types nothing between the <p> tag.

So how can I find if the code includes certain tags ?


Solution

  • Use DOMParser to make the raw HTML string into a Document object it's similar to the DOM tree normally the browser forms while parsing the HTML code

    function isElementPresent(htmlContent, tag) {
      var tagFound = false;
    
      var parser = new DOMParser();
      var parsedHtml = parser.parseFromString(htmlContent, 'text/html'); //mimeType of html is text/html
      var listEls = parsedHtml.all
    
      //all property is [HTMLCollection] holding all the elements (nested or otherwise) that are in the DOM tree
    
      for (var i = 0; i < listEls.length; i++) {
        if (listEls[i].tagName.toLowerCase() == tag) {
          tagFound = true;
        }
      }
      return tagFound;
    }
    
    
    htmlContent = `<div>
    
                <p><b>Demo</b></p>
                <div><h2>Hello</h2></div>
    
              </div>`;
    
    alert( isElementPresent(htmlContent, 'p')     ) //true
    alert( isElementPresent(htmlContent, 'audio') ) //false