3

I have a following string array

["div", "span", "h1", "h2", "h3", "h4", "h5", "p", "br", "a", "strong", "em", "li", "ul", "ol", "b", "i", "u", "hr", "font", "pre", "q", "s", "strike", "blockquote", "sub", "sup"]

I have a string text which also contains HTML tags, I need to verify that the html tags in the paragraph text are out of those defined in string array above. Apart from these if any tags are present error has to be thrown. I saw many methods but couldn't find any simple javascript implementation of these.

1
  • you need to learn about exception handling in javascript to produce errors . Commented Apr 17, 2014 at 10:09

2 Answers 2

1

You would need to parse the HTML, then test all the tags to see if they are matched in the array. I would just parse the HTML, walk through the DOM nodes and test each tagname against the array:

var allowedTags = ["div", "span", "h1", "h2", "h3", "h4", "h5", "p", "br", "a", "strong", "em", "li", "ul", "ol", "b", "i", "u", "hr", "font", "pre", "q", "s", "strike", "blockquote", "sub", "sup"];
var wrapper = document.createElement("div");
wrapper.innerHTML = "<h1>Your HTML here</h1><p>Test</p><span><audio /></span>";
function walk(element) {
    var el = element;
    var len = el.childNodes.length, i;
    for(i = 0; i<len; i++) {
        if(!walk(el.childNodes[i])) return false;
    }
    return !(el.tagName && allowedTags.indexOf(el.tagName.toLowerCase()) === -1);
}
var result = !walk(wrapper);
console.log("Contains invalid tags: " + result);

jsFiddle

Sign up to request clarification or add additional context in comments.

7 Comments

If I use wrapper.innerHTML="Hi I am testing this <span></span>" then it should so true for containing invalid tags but it showing false....I mean for span tag precisely
The walk method returns true if all tags are valid. It returns false if any tags are invalid. I am negating this result so that it displays correctly. So "Contains invalid tags: false" is correct because span is valid.
Even if u give <span></span> as only entry as input it shows false as in it doesn't contains the invalid tags. Even though it's invalid..
@Rajat You're not reading this correctly. Contains invalid tags: false means that your HTML does not contain any invalid tags. Span is a valid tag (second in the array).
Ohh! I am sorry..didn't see span as listed in the array..thanks a lot..it works! :)
|
0

You would have to parse the tags out of the string and then check the tag names against the array; this is discussed in this question. The way of parsing the string depends on your environment, but the topic is discussedin this question.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.