473,785 Members | 2,298 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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('<stro ng>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 6153
jo***********@g mail.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 documentFragmen t, but for the browsers I tested
(Firefox) you can't set it's innerHTML property.

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


Use:

var strongEl = document.create Element('strong ');
strongEl.append Child(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(HTMLstrin g)
{
var d = document.create Element('div');
d.innerHTML = HTMLstring;
var docFrag = document.create DocumentFragmen t();
for (var i=0, len=d.childNode s.length; i<len; ++i){
docFrag.appendC hild(d.childNod es[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***********@g mail.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(HTMLstrin g)
{
var d = document.create Element('div');
d.innerHTML = HTMLstring;
var docFrag = document.create DocumentFragmen t();
for (var i=0, len=d.childNode s.length; i<len; ++i){
docFrag.appendC hild(d.childNod es[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(HTMLstrin g)
{
var d = document.create Element('div');
d.innerHTML = HTMLstring;
var docFrag = document.create DocumentFragmen t();
for (var i=0, len=d.childNode s.length; i<len; ++i){
docFrag.appendC hild(d.childNod es[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(HTMLstrin g)
{
var d = document.create Element('div');
d.innerHTML = HTMLstring;
var docFrag = document.create DocumentFragmen t();

while (d.firstChild) {
docFrag.appendC hild(d.firstChi ld)
};

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

function toDOM(HTMLstrin g)
{
var docBody = document.body || document.docume ntElement;
if (!docBody) return;

if (document.creat eRange && (rangeObj = document.create Range())){
var docFrag, rangeObj;
rangeObj.select Node(docBody);

if ( rangeObj
&& rangeObj.create ContextualFragm ent
&& (docFrag = rangeObj.create ContextualFragm ent(HTMLstring) )){
return docFrag;
}
} else if (
'string' == typeof docBody.innerHT ML
&& document.create Element
&& document.create DocumentFragmen t){
var div = document.create Element('div');
var docFrag = document.create DocumentFragmen t();
div.innerHTML = HTMLstring;

while (div.firstChild ){
docFrag.appendC hild(div.firstC hild)
};

return docFrag;
}

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

<URL:http://xmljs.sourcefor ge.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.create Range
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 createContextua lFragment 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(HTMLstrin g)
{
var docBody = document.body || document.docume ntElement;
if (!docBody) return;

if (document.creat eRange && (rangeObj = document.create Range())){ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^
Yields true in Opera 8.
var docFrag, rangeObj;
rangeObj.select Node(docBody);

if ( rangeObj
&& rangeObj.create ContextualFragm ent ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^
Yields false in Opera 8.
&& (docFrag = rangeObj.create ContextualFragm ent(HTMLstring) )){
return docFrag;
}
} else if (
'string' == typeof docBody.innerHT ML
&& document.create Element
&& document.create DocumentFragmen t){
var div = document.create Element('div');
var docFrag = document.create DocumentFragmen t();
div.innerHTML = HTMLstring;

while (div.firstChild ){
docFrag.appendC hild(div.firstC hild)
};

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.create Range
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 createContextua lFragment 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(HTMLstrin g)
{
var docBody = document.body || document.docume ntElement;
if (!docBody) return;

if (document.creat eRange && (rangeObj = document.create Range())){


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

if ( rangeObj
&& rangeObj.create ContextualFragm ent


^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^
Yields false in Opera 8.
&& (docFrag = rangeObj.create ContextualFragm ent(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.innerHT ML

[...]

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
4754
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 Response.Writes. Are there any tools that will let you design the form then convert that form to Response.Writes that you can further customize with ASP logic? For instance: use Dreamweaver to design the form, then another program to convert to...
9
2900
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 no luck though), and searched through the IRT.ORG Faqs (www.irt.org/script/script.htm). The Javascript is designed to open an popup window and then inside that window call another script which will resize that window. There may be another...
4
3433
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 write and it works fine until she puts it into a function and then calls the function from a button with onClick. This also seems to work OK, with the exception that the page is cleared, and the curser changes (and stays) as an hourglass. In...
2
3059
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 what I'm hoping to achieve. I've never before had to use Javascript closures, but now I do, so I'm making an effort to understand them. I've been giving this essay a re-read: http://jibbering.com/faq/faq_notes/closures.html
6
1657
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 frame like code below. My question is, because this is a new development is it good to use frameset and frame or I can use some thing better. I am looking for expert suggestions on my code below is this a good way to move or I should not use...
19
3827
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
2134
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. Using Safari,my first iteration the script works fine ( indicating that there are 33 form variables ). When trying another dropdown select value, the
5
2227
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, etc.). It is used as follows: addElementToPage("writeroot", "input", "type:button, text:testText, value:testvalue, onclick:test1") The first argument is an ID of the location where the new element it to be appended. The second argument is the type...
1
16975
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 examples I found on the web. Works in IE and mozilla. http://www.imaputz.com/cssStuff/bigFourVersion.html
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10341
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8979
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6741
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5383
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4054
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3656
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2881
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.