473,405 Members | 2,187 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

HTML to DOM Function?

Hey all,

Sorry if this is a newbie question, but does javascript have a built-in
function that will take a string, parse any HTML tags from the string
and return back a DOM element representing the root of the HTML tree
represented by the string? For example is I called
HTML2DOM('<strong>foo</strong>''), it would return the 'strong' element
with one text element child with the value of 'foo'.

Thanks,
-John

Mar 29 '06 #1
5 6135
jo***********@gmail.com wrote:
Hey all,

Sorry if this is a newbie question, but does javascript have a built-in
function that will take a string, parse any HTML tags from the string
If you mean ECMAScript, no. However Microsoft introduced innerHTML some
time ago (with IE 4) and it has been widely copied. You can create DOM
elements from an HTML string by setting an existing element's innerHTML to
the string.

<URL:http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/innerhtml.asp>

and return back a DOM element representing the root of the HTML tree
represented by the string?
No, not even innerHTML will do that. It is a property of an element, so
you have to set the innerHTML of some existing element or create a new
element and set its innerHTML property.

The W3C DOM includes documentFragment, but for the browsers I tested
(Firefox) you can't set it's innerHTML property.

For example is I called
HTML2DOM('<strong>foo</strong>''), it would return the 'strong' element
with one text element child with the value of 'foo'.


Use:

var strongEl = document.createElement('strong');
strongEl.appendChild(document.createTextNode('foo' ));
You could probably create your own function that creates a div element,
sets its innerHTML property, replaces the div with a document fragment
(i.e. attach all the child nodes of the div to the fragment in the correct
order) then returns a reference to the fragment.

Something like (untested):

function toDOM(HTMLstring)
{
var d = document.createElement('div');
d.innerHTML = HTMLstring;
var docFrag = document.createDocumentFragment();
for (var i=0, len=d.childNodes.length; i<len; ++i){
docFrag.appendChild(d.childNodes[i]);
}
return docFrag;
}

innerHTML is not supported consistently in all browsers and feature
detection is difficult. Errors in the HTML string or invalid markup will
cause unpredictable results in different browsers.

--
Rob
Mar 29 '06 #2
RobG said on 30/03/2006 7:33 AM AEST:
jo***********@gmail.com wrote:
Hey all,

Sorry if this is a newbie question, but does javascript have a built-in
function that will take a string, parse any HTML tags from the string

[...]

You could probably create your own function that creates a div element,
sets its innerHTML property, replaces the div with a document fragment
(i.e. attach all the child nodes of the div to the fragment in the
correct order) then returns a reference to the fragment.

Something like (untested):

function toDOM(HTMLstring)
{
var d = document.createElement('div');
d.innerHTML = HTMLstring;
var docFrag = document.createDocumentFragment();
for (var i=0, len=d.childNodes.length; i<len; ++i){
docFrag.appendChild(d.childNodes[i]);
}
return docFrag;
}


Doesn't work. Somehow the stuff added by innerHTML isn't recognised as
DOM objects and so can't be transferred to another element even if the
div is added to the document before modifying its innerHTML property.

The same process works fine if you use DOM methods to create the
elements rather than innerHTML.

There are likely work-arounds, but none of the ones I can think of are
appealing.
--
Rob
Mar 30 '06 #3
RobG said on 30/03/2006 9:59 AM AEST:
RobG said on 30/03/2006 7:33 AM AEST:

[...]
Something like (untested):

function toDOM(HTMLstring)
{
var d = document.createElement('div');
d.innerHTML = HTMLstring;
var docFrag = document.createDocumentFragment();
for (var i=0, len=d.childNodes.length; i<len; ++i){
docFrag.appendChild(d.childNodes[i]);
}
return docFrag;
}


Doesn't work.


I'm an idiot - of course it doesn't work, the childNodes collection is
'live' but my counter (len) isn't. This version *does* work in Firefox
& IE:

function toDOM(HTMLstring)
{
var d = document.createElement('div');
d.innerHTML = HTMLstring;
var docFrag = document.createDocumentFragment();

while (d.firstChild) {
docFrag.appendChild(d.firstChild)
};

return docFrag;
}
Here is a fuller function that makes use of the Gecko range interface
extensions if available:

function toDOM(HTMLstring)
{
var docBody = document.body || document.documentElement;
if (!docBody) return;

if (document.createRange && (rangeObj = document.createRange())){
var docFrag, rangeObj;
rangeObj.selectNode(docBody);

if ( rangeObj
&& rangeObj.createContextualFragment
&& (docFrag = rangeObj.createContextualFragment(HTMLstring))){
return docFrag;
}
} else if (
'string' == typeof docBody.innerHTML
&& document.createElement
&& document.createDocumentFragment){
var div = document.createElement('div');
var docFrag = document.createDocumentFragment();
div.innerHTML = HTMLstring;

while (div.firstChild){
docFrag.appendChild(div.firstChild)
};

return docFrag;
}

return null;
}
To do far more extensive document generation from XML, try XML for <SCRIPT>:

<URL:http://xmljs.sourceforge.net/index.html>

--
Rob
Mar 30 '06 #4


RobG wrote:
Here is a fuller function that makes use of the Gecko range interface
extensions if available:
But your check for that feature needs improvement, document.createRange
is part of the W3C DOM Level 2 Range API which for instance Opera 8
implements besides Gecko. However Opera 8 does not implement the
proprietary Mozilla extension createContextualFragment meaning the way
you have set up your checks below causes Opera to return null from the
function while it could well execute the div.innerHTML branch if you
checks allowed it to get there:
function toDOM(HTMLstring)
{
var docBody = document.body || document.documentElement;
if (!docBody) return;

if (document.createRange && (rangeObj = document.createRange())){ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^
Yields true in Opera 8.
var docFrag, rangeObj;
rangeObj.selectNode(docBody);

if ( rangeObj
&& rangeObj.createContextualFragment ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Yields false in Opera 8.
&& (docFrag = rangeObj.createContextualFragment(HTMLstring))){
return docFrag;
}
} else if (
'string' == typeof docBody.innerHTML
&& document.createElement
&& document.createDocumentFragment){
var div = document.createElement('div');
var docFrag = document.createDocumentFragment();
div.innerHTML = HTMLstring;

while (div.firstChild){
docFrag.appendChild(div.firstChild)
};

return docFrag;
}

return null;
}

--

Martin Honnen
http://JavaScript.FAQTs.com/
Mar 30 '06 #5
Martin Honnen wrote:


RobG wrote:
Here is a fuller function that makes use of the Gecko range interface
extensions if available:

But your check for that feature needs improvement, document.createRange
is part of the W3C DOM Level 2 Range API which for instance Opera 8
implements besides Gecko. However Opera 8 does not implement the
proprietary Mozilla extension createContextualFragment meaning the way
you have set up your checks below causes Opera to return null from the
function while it could well execute the div.innerHTML branch if you
checks allowed it to get there:


Thanks, actually the 'else' is redundant anyway, removing it allows Opera
and similar browsers to fall through to the innerHTML version.

I would probably only use the shorter innerHTML-only method anyway.

function toDOM(HTMLstring)
{
var docBody = document.body || document.documentElement;
if (!docBody) return;

if (document.createRange && (rangeObj = document.createRange())){


^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^
Yields true in Opera 8.
var docFrag, rangeObj;
rangeObj.selectNode(docBody);

if ( rangeObj
&& rangeObj.createContextualFragment


^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Yields false in Opera 8.
&& (docFrag = rangeObj.createContextualFragment(HTMLstring))){
return docFrag;
}
} else if (
Remove the 'else' and just use 'if', since if the above if loop is executed
the function will return from there anyway:

}
if (
'string' == typeof docBody.innerHTML

[...]

I only included the range stuff as a bit of an experiment. :-)
--
Rob
Mar 30 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: TinyTim | last post by:
I'm a newbie at ASP & HTML. It seems that when you use server side code and you're going to return a customized HTML form with several fields and labels, you have to do an extensive amount of...
9
by: Robby Bankston | last post by:
I'm working on some code and am running into brick walls. I'm trying to write out Javascript with Javascript and I've read the clj Meta FAQ and didn't see the answer, read many similar posts (with...
4
by: frogman042 | last post by:
My daughter is playing around trying to learn JavaScript and she wrote a small program that prints out a message in increasing and decreasing font size and color changes. She is using document...
2
by: Jake Barnes | last post by:
Using javascript closures to create singletons to ensure the survival of a reference to an HTML block when removeChild() may remove the last reference to the block and thus destory the block is...
6
by: Ashok | last post by:
Hi, I am starting a new project to build a software product using APS.NET 2.0. In past I have used "frameset" and "frame" to build pages. My current requirements I have coded using frameset and...
19
by: thisis | last post by:
Hi All, i have this.asp page: <script type="text/vbscript"> Function myFunc(val1ok, val2ok) ' do something ok myFunc = " return something ok" End Function </script>
2
by: justplain.kzn | last post by:
Hi, I have a table with dynamic html that contains drop down select lists and readonly text boxes. Dynamic calculations are done on change of a value in one of the drop down select lists. ...
5
by: dwmartin18 | last post by:
Hello everyone. I have quite the puzzling problem with a script I have been working on lately. I have created a function that can be called to create a new html element (e.g. input, select, div,...
1
by: since | last post by:
I figured I would post my solution to the following. Resizable column tables. Search and replace values in a table. (IE only) Scrollable tables. Sortable tables. It is based on a lot...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.