innerXHTML

A replacement for the non-standard innerHTML tool used for manipulating the DOM.

Web developers working with Javascript and the Document Object Model will know that development can often be a longwinded process. The large selection of standardised tools we have available at our disposal, as stipulated by the W3C, allow us to manipulate the DOM with an unprecedented level of precision. However this precision comes at the expense of time, and unfortunately the W3C were not so generous in providing tools which could forfeit precision for speed and ease of use.

Enter Microsoft with it's non-standard innerHTML function. innerHTML benefits for all the latter reasons; it is easy and incredibly quick to use. Despite lacking in precision it remains a popular tool of choice for many DOM scripters. Even its exemption from the W3C's specification has not deterred many web developers from utilising it. innerHTML enjoys good cross-browser support, but like all non-standard aspects of web design this is unlikely to remain so come future advancements in browser technology. Such change will no doubt render all script using innerHTML inoperable. We need to find an alternative; a standardised innerHTML.

What is innerXHTML?

innerXHTML is a glorified DOM read/writer. It is my answer to the non-standard innerHTML, the result of too many late nights in front of the computer screen and the aspirin to many of my DOM scripting headaches. It utilises existing functionality, all supported by the W3C, to read and write to the DOM. In doing so, innerXHTML gains all the benefits of innerHTML without the baggage; speed and ease of use, whilst keeping within the boundaries of global standardisation.

innerXHTML is not a document copier; it does not fetch exactly what the document contains, character for character in a zombie-like fashion. innerXHTML reads the document node tree, returning a text string of markup to the document's equivelent. Likewise, innerXHTML writes to the DOM with the correct approach; intelegently, node by node, not as one big string. You wont find any document.write() here!

How does innerXHTML work?

It is split into two functions. The first function innerXHTML acts as the interface between the two. It reads the document node tree and returns markup in plain text to the source that called it. The second function translateXHTML serves the purpose of translating XHTML and XML code from a plain text string into nodes for insertion into the document object model. translateXHTML is the more processor-heavy function and is additionally more complex in structure. You can operate translateXHTML independently from innerXHTML, though I don't recommend this.

Using innerXHTML to read from the DOM

I have built innerXHTML to work much like innerHTML. Once the .js file is referenced by your markup document using a <script src=""> you can use innerXHTML like any other function:

var container = document.getElementById('container');
var code = innerXHTML(container);

This snippet of script above, will find the node with an id attribute of 'container' and, using the innerXHTML function return it's entire content in a plain text string - markup 'n all. The one and only parenthesis is the mandatory source element from which we are reading. Remember, innerXHTML will return the markup of whatever nodes the source element contains. Data returned will not include the source element's own tag and attributes, mirroring the non-standard innerHTML. Lets take a quick look at the aforementioned innerHTML for execution comparison:

var container = document.getElementById('container');
var code = container.innerHTML;

As you can see innerXHTML takes a slightly different approach, but ultimately remains just as easy to use.

Using innerXHTML to write to the DOM

Whilst reading has its benefits, innerXHTML really comes into its own over regular, hand-written document.createElement() techniques when writing to the DOM. Traditionally every element, and sub-element, and sub-sub-element has to be individually created by you the developer, in addition to each element's potentially multiple attributes and contained text nodes. This is a labouring process to say the least.

Using innerXHTML all you are required to provide is the plain string of markup. The function will do the hard work of reading and translating the markup into DOM nodes and inserting them into your document for you. Let's take a look:

var container = document.getElementById('container');
var markup = '<div id="content"><p class="text">Hello world!</p></div>';
var code = innerXHTML(container,markup);

Our innerXHTML function accepts two parentheses this time; the mandatory source element in which we are writing, and secondly the string of text markup to replace any existing content therein. The above code fragment finds the element with an id of 'container' and, via innerXHTML, inserts into it a <div> with an id attribute of 'content'. Into that it appends a <p> paragraph element with a child text node of 'Hello World!'. Don't worry about any document.createElement(); messing about; innerXHTML takes care of this all for you. The variable code here is optional and will now contain exactly the same text markup as you put into the function.

Some people use innerHTML for the purpose of quickly emptying an element of its children. This is a perfectly good use of innerXHTML with a command such as innerXHTML(container,' ');. Just be aware that a value must be passed for the second parenthesis; ideally, a space. Technically this means you are not emptying the source element completely, but rather replacing its content with a single space text node. However for practical use this should serve the purpose.

Additional Information

I have repeatedly streamlined innerXHTML to run as efficiently as possible, and from earlier (you could call them alpha ;) ), development versions the results do show. innerXHTML is quick in operation and can construct full pages from markup easily, depending on the computer and browser speed. It is naturally not as fast as the non-standard innerHTML, but the differences are in miliseconds, again depending on the quantity of code. Speed tests coming soon.

Please remember that this function expects only code adhering to web standards. Passing the function non-standard markup or trying to read an invalid document will likely result in process failure!

Additionally I have taken time to ensure innerXHTML is as cross-browser compatible as possible, hence some structural changes along the development line. Below is a table of browser support information. Please note that the browsers listed below are the only ones that I have tested innerXHTML on. If a browser you are looking for is not listed here then it will not mean that innerXHTML does not run, it simply means I have not tested it as yet. If you do undertake any further testing and have feedback then please get in touch with me. It's all good :)

Browser Supported? Additional Comments
IE7 Windows Full support (Minor proprietary characteristics) Some elements, such as <img />, are given extra attributes when read with innerXHTML. However, further testing has found this causes no fracture to the functionality and the differences are likely to go unnoticed.
IE6 Windows Full support (Minor proprietary characteristics) 'on' events (onclick, onmouseover, etc.) do not work when translated from text into document.Fixed in v0.4+.
See IE7 (above).
IE5 Windows Virtually full support In addition to the IE6/7 proprietary characteristics (detailed above) IE5 does not translate <!--comments-->. However markup created on-the-fly with JS does not appear in the source document anyway, so unless you plan to insert markup then read it back into a string, you're not going to notice a thing :)
FF Windows Full support
Flock Windows Full support
FF Mac Full support
Safari Mac Full support
Camino Mac Full support
Opera Windows Full support (Minor proprietary characteristics) Writes elements using uppercased tag and attribute names, and enters unnecessary attributes such as shape="rect". However, further testing has found this causes no fracture to the functionality and the differences are likely to go unnoticed..

Important: innerXHTML translates and inserts XML into the DOM without a problem in all browsers. It reads and returns XML correctly in most browsers too; every one except Microsoft Internet Explorer 5&6. This is entirely down to poor DOM support by IE. For the same reason IE 5&6 will not read any part of the document node tree containing element(s) it does not recognise. In practical use this basically means by example that innerXHTML will not read any part of the document tree containing the <abbr> element in Internet Explorer 6 or less. Internet Explorer 7 has corrected the problem.

Update: 21/03/2007 - Version 0.4 Released

Almost 6 months following it's release innerXHTML has transcended to version 0.4. The updates make the function slicker, easier and more cross-browser compatible than ever. They are:

$appendage argument added

The function now accepts three arguments rather than just two. The third argument is $appendage and can dictate where in the parent node you place your inserted markup string. Let's use this document slice as the basis for our examples:

<div id="content">
<h2>About Google</h2>
<p>Google was co-founded by Larry Page and Sergey Brin while they were students at Stanford University.</p>
<p id="closing_paragraph">The name "Google" originated from a misspelling of "googol", which refers to 10<sup>100</sup> (the number represented by a 1 followed by one hundred zeros).</p>
</div>

innerXHTML's third argument now accepts four value types:

  1. Default boolean false: Empties the parent container.
  2. Child node: Enter a child node and the markup string you pass will be inserted before it.
  3. String ID: As above, except the child is located using the ID of the string you pass.
  4. Any other true value: Append the string markup you pass after existing parent's children.

Respective examples:

// This will empty the DIV with a id of 'content'  before inserting the link
innerXHTML(document.getElementById('content'), '<a href="#">click me</a>');
// This will insert the link before the first paragraph
innerXHTML(document.getElementById('content'), '<a href="#">click me</a>', document.getElementsByTagName('p')[0]);
// This will insert the link before the second paragraph
innerXHTML(document.getElementById('content'), '<a href="#">click me</a>', 'closing_paragraph');
// This will append the link into the DIV after the existing content
innerXHTML(document.getElementById('content'), '<a href="#">click me</a>', true);
First $source argument now accepts string ID

Speed things up by entering the parent id as the first argument, rather than a node reference. Using the last snippet as an example:

innerXHTML('content', '<a href="#">click me</a>');
'on' events now supported by all browsers

Does what it says on the tin: Internet Explorers now also support inserted on events. Example:

innerXHTML('content', '<a href="#" onclick="alert(\'Hello World\');">click me</a>');

I'd like to thank Stef Dawson for his most appreciated contributions and feedback. He's made the 'on' event patch in IE a reality - cheers Stef :).

If anyone else has any ideas for improving innerXHTML then don't hesitate to let me know. Let's put an end to this non-standard bollocks once and for all.

Callin' it a do

Take a copy of the innerXHTML script and feel free to leave any comments or thoughts you may have. At 150 lines innerXHTML weighs in at just under 6kb and shouldnt burden your website much. I've released this software under the Creative Commons Attribution-Share Alike 3.0 License.

It is intended only to reduce DOM script development time, and I hope this is what it achieves. If you do happen to uncover any elusive bugs I have missed then please drop me an email. Otherwise enjoy :)

Download IconDownload innerXHTML (v0.4)

Dated: 14/10/2006. Filed under: Projects and Web Design.


Comments

On 15th October 2006 P.J. Onori said:
Gravatar image
Wow, this seems very impressive. As someone that has been forced to do more Javascript than is within my comfort zone, something like this is a huge plus. Awesome writeup man.
On 15th October 2006 rasmus said:
Gravatar image
a wee bit shorter method for mozilla browsers:


Element.prototype.innerXHTML = function (xhtml) {
if (xhtml) {
for (var i=0, n; n=this.childNodes[i]; i++) this.removeChild(n);
var r = document.createRange();
r.selectNode(this);
var x = r.createContextualFragment(xhtml);
this.appendChild(x);
return x;
}
else {
var xhtml = "";
for (var i=0, n; n=this.childNodes[i]; i++) xhtml += (new XMLSerializer()).serializeToString(n);
return xhtml;
}
};


used like this:

var xhtml = "hello, world";
var element = document.getElementById("MyDiv");
element.innerXHTML(xhtml);

if no arguments are passed to the innerXHTML method it returns the existing html from the element.

alert(element.innerXHTML());
// alerts "hello, world".
On 16th October 2006 Nate Cavanaugh said:
Gravatar image
For those of us who use Prototype (http://prototype.conio.net), here is a handy tip for integrating this function to the DOM methods.

Add this to your javascript:
Element.addMethods({
innerXHTML: function(element, content) { return innerXHTML(element, content); }
});

Now you can quickly read and set the innerHTML of the document like this:

$('container').innerXHTML(); // read the innerHTML
$('container').innerXHTML('test'); // set the innerHTML

Just thought it might help some folks :)
On 16th October 2006 Fredrick said:
Gravatar image
Great piece of javascripting Steve!! Maybe we will be seeing the last of innerHTML sooner than we all thought... ;-)
On 16th October 2006 Stoyan said:
Gravatar image
Good job, thanks for sharing!

I tried to address the issue with a tool to create DOM calls from HTML, sort of like code generator. My approach doesn't use regex, but tries to create an XML document from the HTML string, therefore forcing you to pass only valid XHTML, otherwise it won't work. My tool is at http://www.html2dom.com/
On 17th October 2006 Jonathan Snook said:
Gravatar image
The chances of innerHTML disappearing from browsers is slim to none. If anything, it'll simply become a part of future standards.

Good job on the script, though. :)
On 17th October 2006 Steve Tucker said:
Gravatar image
Thanks for the positive comments guys :)

@Jonathan: I wish they would make innerHTML a standard - would make life for DOM developers a whole lot easier
On 17th November 2006 Adam said:
Gravatar image
Thanks Man...you just made my week.
On 21st November 2006 pilyoto said:
Gravatar image
Thanks for sharing your work! About the 'on' events not working, is there any way to get around this?
On 23rd November 2006 Steve Tucker said:
Gravatar image
Not directly in Explorer - ive tried. The only way to do on events is by executing your innerXHTML call, then adding the on event to the element afterwards using, say, an ID as a handle.
On 3rd December 2006 Tommy said:
Gravatar image
Awsome work. This is going to be really useful!

Keep it up
On 7th December 2006 Florian said:
Gravatar image
Great work Steve, thanx for sharing!! What is the load time for this function in comparison to innerHTML? F.
On 31st January 2007 Chris said:
Gravatar image
I've tried using this method on flash markup, such as and it doesn't work. Firefox doesn't do anything, IE6 reports Unexpected call to method or property access. If I use markup like some text, it works fine. Any suggestions?
On 20th March 2007 Bloke said:
Gravatar image
Awesome function, thank you: just what I've been after. I've extended it slightly though:

1) Added a third 'append' argument. If true, the contents of the source element are not cleared; although not truly in the spirit of innerHTML, it's particularly useful for logging purposes or showing users a history of what they've done.

2) The source argument can now be a string as well; if it is, the element is looked up via a call to document.getElementById(). Again, just a convenience.

3) I've kludged a way to handle 'on' events in IE6. It's not pretty and I'd love to find a way of making it dynamically use the attName as the handler instead of the ugly switch() statement. Maybe someone else can do it? I spent the afternoon hacking it this far and I'm sick of the sight of IE6!

It does the setAttribute as normal for compliant browsers and then adds an anonymous function directly to the element's onclick for IE6 and other naughty/stupid browsers.

btw, the $ in front of the variable names played havoc with eval() and the regexes as I was testing so I removed it. Upon reflection I guess it can go back in (possibly with some escaping) if you miss it.

Have a look at the code at http://www.stefdawson.com/downloads/innerXHTMLplus.js

Thanks again, this function has saved me tonnes of repetitive DOM programming, with the advantage that the DOM structure is retained - superb!
On 21st March 2007 Steve Tucker said:
Gravatar image
Thanks, Stef! That's some really great work. It's uncanny that you submitted this now, because I've been about to release v0.4 with $append argument you suggested, only with a little more flexibility (see documentation update for details).

Really awesome work though with the 'on' events - I'd never have though about eval as a way around that problem in IE. I've fixed the dynamic event setting too, so it's much cleaner and more flexible. Check the source code.

Also, unusually, I had no such problems with the $ character I use on variable names. Very strange?

Cheers mate :)
On 22nd March 2007 Jerry said:
Gravatar image
Thanks so much for sharing this its going to save me loads of programming time!
On 23rd March 2007 Thor Larholm said:
Gravatar image
I don't see why you would not add this a a property on all the HTML elements. Here is a simple addition to your script that defines a gettable and settable property in IE and moz/firefox:

For mozilla, add this script


if(typeof HTMLElement!="undefined" && typeof HTMLElement.prototype!="undefined" && typeof HTMLElement.prototype.__defineGetter__=="function"){
HTMLElement.prototype.__defineGetter__("innerXHTML",function(){ return innerXHTML(this) });
HTMLElement.prototype.__defineSetter__("innerXHTML",function(S){ return innerXHTML(this,S) });
}


For IE, add this style declaration:

* { behavior: url(innerxhtml.htc) }

innerxhtml.htc contains:



function putxhtml(S){ return innerXHTML(element,S) }
function getxhtml(){ return innerXHTML(element) }
On 18th May 2007 betatester said:
Gravatar image
Your function is useless,
if you do some tests on IE6 you immediately see that returning the innerXHTML of a node like this one

<BODY>
<DIV>
<IMG src="something.jpg">
</DIV>
</BODY>

would return attributes like:
loop, width, height, start
for the IMG node even if they are not specified.
On 20th May 2007 Steve Tucker said:
Gravatar image
Betatester to start with your markup is invalid, which suggests you havent even read the full documentation before commenting. You're right that extra attributes are added by IE6, but I couldn't disagree more with your suggestion that this somehow renders the function useless. It's highly unlikely these extra proprietary attributes will ever cause any problems.

In addition the function is most useful for writing DOM notes from string markup, and in this area it absolutely fine also. For those who want to stick 100% to standards the function is anything but useless.
On 21st May 2007 betatester said:
Gravatar image
I did not mean to be rude.
I appreciated your code and the fact that you made it public.

I'm only saying you should point out loud and clear somewhere in your doc page that this function returns for images (and probably also for other elements) attributes that are not really defined the in source html code of the page.

These kind of functions are very useful to make CMS, where the client gets the content of a page using innerHTML or yours innerXHTML and sends it to the server.
It would be very useful to get the content in clean XHTML rather than getting the innerHTML's mess and having to clean it up everytime.

But the main difference is that the innerHTML mess can still be cleaned up by using js code to make it XHTML compliant, whilest the XHTML returned by your function is difficult to clean up. For example: how do we know that the width/height attribute of an image element is not really defined in the page, but it's simply the innerXHTML function that is returning it by mistake???


Moreover I did not mention speed, innerHTML is much faster than walking throught the DOM recursively.



BTW: i don't uderstand why my markup is invalid, I could call:

var s = innerXHTML(document.body);

to return the XHTML source of the page.
On 21st May 2007 Steve Tucker said:
Gravatar image
Fair point made betatester. You are right that IE adds unwanted attributes to images (and like you say, probably other elements). I did not spot this before in my testing, but I'll be sure to make a note of it now.

I am also well aware that this function is not as fast as innerHTML; it never pretends to be and I've made this clear in the documentation. Im to be doing some speed tests soon whenever I get the the time, which should be interesting.

By invalid code I mean that your tags are uppercased and your image has not been closed properly.

Anyway thanks for bringing these IE characteristics to light. I just need to find out exactly which elements are causing the problems in IE and resolve them.
On 31st May 2007 Stephan said:
Gravatar image
Hi. Thanks for the great script. I'm testing it now and so far it's working a treat (although there are some issues using it from an IE addon, which I'll write about later).

I was wondering why there's a call to translateXHTML($string,false) in v0.4. What's the false for?
On 5th June 2007 Steve Tucker said:
Gravatar image
Glad you're finding it useful, Stephan. Well spotted - the second 'false' argument there is actually residue from earlier versions of innerXHTML - 0.1 and 0.2, that I never published open source. I obviously missed taking that 2nd boolean value out when I rebuilt the script ;)
Thanks for highlighting it
On 10th July 2007 Scottie said:
Gravatar image
Phenomenal. I've been banging my head against IE6 and Firefox returning different values when using innerHTML to read parts of the DOM structure into a String (for passing to a Flash application). Your script just saved my life.

Thanks!
On 18th July 2007 Pinna said:
Gravatar image
Dude you really really really fucking rock! great job! your solution is neat, simple, and works quite fast too! :^) I struggled for several hours looking for an alternative to innerHTML, and now, here it is. THANKS!

On 16th August 2007 scott said:
Gravatar image
Very nice javascript module - this will come in very handy... Thanks!
On 21st August 2007 Steve Tucker said:
Gravatar image
My pleasure guys, thanks for the feedback :)
On 21st August 2007 scott said:
Gravatar image
Again, thanks for the awesome script...

Just wanted to let you and your readers in on a quirk I just found using this script in IE7.

If you are going to use innerXHTML to insert a table, it must have a TBODY tag. While it is optional when using innerHTML (probably because IE7 puts it there automatically), it is not optional when building a table through DOM methods - your table won't be visible and you'll be quite confused as to why (I know I was!).

Hope this saves someone some time :-)
On 11th September 2007 Shev said:
Gravatar image
Steve, thanks for sharing an awesomely useful bit of javascript that's saving the hair and sanity of fellow developers.

Quick question: does innerXHTML write character entities out correctly? e.g. I'm trying to have it write to a span node with the call:

innerXHTML(document.getElementById("usi_separator")," ·");

...but what's seen in FF2 and IE6 are the literal character codes, " ·" instead of the substituted character entities of a space and a floating dot. Is there a way to get the desired result? Thanks again for a great tool.
On 6th November 2007 Nelle said:
Gravatar image
Thank you ....
Very much ....

i have noticed some problems with number html entities like ®

I have a cms system where all mailto addreses are entity encoded before saving into database ...

a link with href attribute = mailto:(entities)
when parsed with innerXHTML looses the ; from the last entity

however i can use innerhtml for reading the string and innerxhtml for writting it ..
On 9th December 2007 Steve Tucker said:
Gravatar image
Hi Nellie, I'll be looking into this problem as soon as I get some time free! I've had a couple of other people return with issues of a similar nature. However, for the time i'm glad you can find good use for it :)
On 22nd February 2008 Amiri Barksdale said:
Gravatar image
WOW! This fixes the innerHTML-IE7-table element insertion problem! Thanks a bunch. Excellent work.
On 9th March 2008 cabrera said:
Gravatar image
I love this script and I found another great use for innerXHTML. This worked great for an xml/xslt site in doing google adsense...

in combination with...

document.write=function(e){innerXHTML(IDorElement,e,true);};

and or this method

document.write = function(str,IDorElement){

var thirdP = true;

if(!IDorElement){
var sElements = document.getElementsByTagName("SCRIPT");

var currentS= sElements[sElements.length - 1];

var pElement = currentS.parentNode;
thirdP = currentS;
IDorElement = pElement;
}
innerXHTML(IDorElement,str,thirdP);
}

hope this helps somebody out there
On 5th November 2008 Roman said:
Gravatar image
Cool, but there is problem with IE. It clearing tabs and spaces in source's body, when read it from html.
Could you fix it?
On 16th December 2008 rgrwkmn said:
Gravatar image
Thanks for the script, Steve! I modified it so you can read and write styles and scripts with safari, firefox and IE7 (was busted in IE7 in the state I found it). Also modified it so it doesn't break on comments containing html and new lines (although breaking on new lines was probably my fault).

I'm crap with regex, so you may want to clean some of it up for your own use. I also use a very sloppy global variable called innerxhtmlLastTag. You'll see that it's ugly, but it works :) This thing is ready to rip up some DOM!

There is one special addition I made for jquery users: IE really likes to add mysterious jquery attributes to just about everything so to avoid this un-comment lines 46, 48, 106 and 140.

You can get the improved script here: http://rogerwakeman.net/innerxhtml.js
On 3rd January 2009 Heiko Weber said:
Gravatar image
Hi Steve,

you should possibly add a

if ($string == $returned[1])
break;

into the while($string)-loop at the end of innerHTML, just in case translateXHTML is unable to modify the given string any further ... otherwise the script is catched in an endless loop :-)

Heiko
On 29th March 2009 Hostile Fork said:
Gravatar image
Thanks for sharing!! These things keep evolving so I'm never sure what the "right" API call is, but at least this works in the code I've got. :)

Would be nice, though, if it would do the optimization of single elements e.g "(br)" and turn them into "(br /)" instead of "(br)(/br)"...
On 2nd September 2009 SatanZ said:
Gravatar image
really nice piece of work fixed my problem of ... getting changed to ...
when using innerhtml. and i feel the same as Fork about the (br) tags anyway good job
On 2nd September 2009 SatanZ said:
Gravatar image
ment my (li) ... (/li)

being changed to (li) ...
On 17th September 2009 Joe said:
Gravatar image
This function saved my ass. THANK YOU!!
On 27th December 2009 David said:
Gravatar image
Hi! Is it possible to replace the root node of a file.

I'm trying to replace the whole current page with the content downloaded via ajax... but document.write() doesn't work.

THANK YOU !!
On 14th April 2010 betatester said:
Gravatar image
What's up with innerXHTML, any new release. You are smart guy, you should join stackoverflow.com
On 19th May 2010 Kleber Correia said:
Gravatar image
WOOOOOWWWW!!!! You saved my day!!!
CONGRATULATION!!! Thanks by colaboration!
On 21st June 2010 Charles Majola said:
Gravatar image
You just saved me many sleepless nights, Thanks a lot dude
On 26th July 2010 website development delhi said:
Gravatar image
very good knowledge has been given about the designing of the site.
Thanks
http://www.airia.co.in/
On 22nd January 2011 John Kerns said:
Gravatar image
Nice code, but had to modify it a bit to output content of script tags in IE 7 & IE 8. I inserted these lines near the beginning of innerXHTML:

if ($children.length == 0
&& $source.nodeName.toLowerCase() == 'script')
return $source.text;
On 4th February 2011 Rob P said:
Gravatar image
Hi Steve,

I'm a latecomer to this function and tried it to solve a requirement. I use innerXTML to retrieve the content of a element ( a dummy template element used to clone new table rows). This template element has a varying number of child nodes with id and name attributes that have a dummy value. The innerXHTML function returns the inner HTML correctly, allbeit with some extra attributes, and I replace the dummy id values with the correct value for the new row. I then use innerXHTML to write the modified inner html back to a new tr element and append to a table. On writing back however all the "onchange" attributes of the child elements have been removed. I am using v0.4 which implied this had been fixed. Any suggestions?

regards
Rob
On 11th February 2011 Johnny said:
Gravatar image
Style attribute "background-image:url(...)" was causing a double quote issue because of the cssText property.

The rendered XHTML was like this: style="background-image:url("...")"; therefore causing the style to be closed? Some XHTML parsers did not love that...

In line 36 I just added the following:

// Do not allow " to be in string
var $style = $children[$i].style.cssText.toLowerCase().replace(/"/g,'');
$xhtml += ' style="'+$style+'"';
On 24th March 2011 Ihor Filakhtov aka Greshnik said:
Gravatar image
Nice function. Working around the same solution.

some advices:
* element.style.float is wrong for JS (float is reserved keyword) should use element.style.cssFloat;
* Easier regular expressions:
[a-z]{0,1} is the same as [a-z]?
[a-z]{1,} is the same as [a-z]+
[a-z]{0,} is the same as [a-z]*
[a-z]{1} is the same as [a-z]
* "on" events can be set via $new_element[$attName] = new Function ($attValue);

I got some ideas from your solution. Thanks!
On 24th March 2011 Ihor Filakhtov aka Greshnik said:
Gravatar image
BTW you can use:

do {
$attribute...
} while ($attribute);

vs

var $attribute = true;
while ($attribute) {...}

;)
On 24th March 2011 Ihor Filakhtov aka Greshnik said:
Gravatar image
Also

/regexp/.exec (str)

work faster than

str.match (/regexp/)

because it is remember only first match (usable for your way of attributes testing)
On 24th March 2011 Ihor Filakhtov aka Greshnik said:
Gravatar image
One more advice, coz i really like your solution (transform css-properties from css to js):

while ((re = prop.indexOf ("-")) !== -1)
prop = prop.replace (/-[a-z]/, prop.substr (re + 1, 1).toUpperCase ());

prop - is CSS-property name here...
On 7th June 2011 MK said:
Gravatar image
Very useful, but there is a problem at least with tag: It is doubled, because it's returned as , which is wrong. All the non-closing tags have the same thing: area, br, col, embed, hr, img, input, link, meta, param.

Journal Archive

Search the archives of this website for design and web-related articles.

Search Archive:

Miscellaneous

Other fluff that doesn't fit within any other category.

XHTML | CSS | 508