0

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 ?

Vinay
  • 7,442
  • 6
  • 25
  • 48

3 Answers3

0
var x = document.getElementById(“myId”).value;
if (x.includes(“html”) && x.includes(“ ”) == true) {
    alert(“html tag added”)
} else {
    alert(“that tag does not exist”)
}
0

try :

var myHtml = 'Aenean lacinia bibendum <a href="/life">life</a> sed consectetur. <a href="/work">Work</a> quis risus eget urna mollis ornare <a href="/about">about</a> leo.';

var result = myHtml.search(/<\s*a[^>]*>(.*?)<\s*\/\s*a>/g);
if (result >-1) {
    alert('right!');
} else {
     alert("wrong");
}

you can replace "a" with other tag name like "p"

foad abdollahi
  • 1,733
  • 14
  • 32
0

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
Vinay
  • 7,442
  • 6
  • 25
  • 48