Coder Social home page Coder Social logo

pure-javascript-html5-parser's Introduction

Pure JavaScript HTML5 Parser

A working demo can be seen here.

Credit goes to John Resig for his code written back in 2008 and Erik Arvidsson for his code written prior to that.

This code has been updated to work with HTML 5 to fix several problems.

4 Libraries in One!

A SAX-style API

Handles tag, text, and comments with callbacks. For example, let’s say you wanted to implement a simple HTML to XML serialization scheme – you could do so using the following:

var results = "";

HTMLParser("<p id=test>hello <i>world", {
  start: function( tag, attrs, unary ) {
    results += "<" + tag;
 
    for ( var i = 0; i < attrs.length; i++ )
      results += " " + attrs[i].name + '="' + attrs[i].escaped + '"';
 
    results += ">";
  },
  end: function( tag ) {
    results += "</" + tag + ">";
  },
  chars: function( text ) {
    results += text;
  },
  comment: function( text ) {
    results += "<!--" + text + "-->";
  }
});

results == '<p id="test">hello <i>world</i></p>"

XML Serializer

Now, there’s no need to worry about implementing the above, since it’s included directly in the library, as well. Just feed in HTML and it spits back an XML string.

var results = HTMLtoXML("<p>Data: <input disabled>")
results == '<p>Data: <input disabled="disabled"></p>'

DOM Builder

If you’re using the HTML parser to inject into an existing DOM document (or within an existing DOM element) then htmlparser.js provides a simple method for handling that:

// The following is appended into the document body
HTMLtoDOM("<p>Hello <b>World", document)
 
// The follow is appended into the specified element
HTMLtoDOM("<p>Hello <b>World", document.getElementById("test"))

DOM Document Creator

This is a more-advanced version of the DOM builder – it includes logic for handling the overall structure of a web page, returning a new DOM document.

A couple points are enforced by this method:

  • There will always be a html, head, body, and title element.
  • There will only be one html, head, body, and title element (if the user specifies more, then will be moved to the appropriate locations and merged). link and base elements are forced into the head.

You would use the method like so:

var dom = HTMLtoDOM("<p>Data: <input disabled>");
dom.getElementsByTagName("body").length == 1
dom.getElementsByTagName("p").length == 1

While this library doesn’t cover the full gamut of possible weirdness that HTML provides, it does handle a lot of the most obvious stuff. All of the following are accounted for:

Unclosed Tags:

HTMLtoXML("<p><b>Hello") == '<p><b>Hello</b></p>'

Empty Elements:

HTMLtoXML("<img src=test.jpg>") == '<img src="test.jpg">'

Block vs. Inline Elements:

HTMLtoXML("<b>Hello <p>John") == '<b>Hello </b><p>John</p>'

Self-closing Elements:

HTMLtoXML("<p>Hello<p>World") == '<p>Hello</p><p>World</p>'

Attributes Without Values:

HTMLtoXML("<input disabled>") == '<input disabled="disabled">'

pure-javascript-html5-parser's People

Contributors

blowsie avatar lucapierobon avatar munawwar avatar sundeepnarang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pure-javascript-html5-parser's Issues

<a> incorrectly classified as block elements

In the following lines of htmlparser.js, <a>-tag seems to be classified as a block element.

// Block Elements - HTML 5
var block = makeMap("a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video");
// Inline Elements - HTML 5
var inline = makeMap("abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");

But the w3c spec and this summary suggest it should be an inline element instead.

This causes an issue with parsing <a>-tag within an inline element, forcing the latter tag to close before the <a>-tag begins.

Minimal examples:

HTMLtoXML('<div>foo <span>bar</span> buz</div>')
// returns "<div>foo <span>bar</span> buz</div>"

HTMLtoXML('<span> hi  <a href=\"https://www.w3schools.com\">Visit W3Schools.com!</a></span>')
//returns "<span> hi  </span><a href=\"https://www.w3schools.com\">Visit W3Schools.com!</a>"

when an <a> tag contains one or <div> tags, all child nodes of the <a> tag are returned by the parser *after* the closing <a> tag

For example, this HTML:

<a href="http://foo.com/">
    <div id="mydiv">divContent</div>
    <span id="myspan">spanContent</span>
    otherContent
</a>

parses to:

<a href="http://foo.com/">
    </a><div id="mydiv">divContent</div>
    <span id="myspan">spanContent</span>
    otherContent

HTML 5 states that the element "may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links)"

http://www.w3.org/TR/html5/text-level-semantics.html#the-a-element
http://stackoverflow.com/questions/1827965/is-putting-a-div-inside-an-anchor-ever-correct

Optional closing tag element closing issues.

p closes before div, ul, ol, table, hr, blockquote opening tags, and li closing tags (which this isn't working 100% for some reason, leading to long strings of </p></li> before UL/OL close.). There may be other cases I've missed.

li tags close before other li tags, but not if they're in another ul or ol context (you don't want <li><ul></li><li>)

Otherwise this works fairly well and saves a lot of time closing tags!

svg error

svg animate attributename no attributeName repeatcount no repeatCount

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.