Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Old 11-18-2003, 07:39 PM   PM User | #1
wac
Regular Coder

 
wac's Avatar
 
Join Date: Sep 2002
Location: Cary, North Carolina, USA
Posts: 357
Thanks: 0
Thanked 0 Times in 0 Posts
wac is an unknown quantity at this point
How does one add things to documentFragment

The Netscape javascript DOM ref (Gecko DOM ref)
I see the following code (which is exactly what I want to do)

frag = document.createDocumentFragment();
frag.write(“<div>Moveable Div</div>”);

However, when I try this in IE6, I get an 'Unspecified Error' javascript error. I also don't see any methods for document fragment in the W3C DOM docs. I guess I could use innerHTML and do the following. Except now I have to create a specific tag name where as with document fragment, I did not have to.

node = document.createElement("DIV").innerHTML = "Moveable Div"

Of course the "Moveable Div" string would eventually get replaced by more complex HTML code. Would the innerHTML mechanism work? Is this the only workaround in IE for the missing functionality of document fragments? From what I saw in the W3C docs there didn't seem to be anyway to populate a document fragment with anything other than to use the standard methods on Node. So why would anyone bother with DocumentFragment when they can do the same thing with Node ???
__________________
Wayne Christian
wac is offline   Reply With Quote
Old 11-19-2003, 12:46 AM   PM User | #2
brothercake
Senior Coder


 
Join Date: Jun 2002
Location: near Oswestry
Posts: 4,509
Thanks: 0
Thanked 0 Times in 0 Posts
brothercake is an unknown quantity at this point
I've never used documentFragment personally. What's the matter with having to specify an element name when you create an element? - you did that in the first example, only difference being you wrote it into the document fragment as text.

Whenever you create a node, you can create a reference to it, that will later allow you to modify its contents:

var newDiv = document.createElement('div');
newDiv.innerHTML = 'Hello world';
document.body.appendChild(newDiv);

But remember that innerHTML itself is not a standard technique; the DOM technique, in this example, is to create and append a text node:

var newDiv = document.createElement('div');
newDiv.appendChild(document.createTextNode('Hello world'));
document.body.appendChild(newDiv)
__________________
"Why bother with accessibility? ... Because deep down you know that the web is attractive to people who aren't exactly like you." - Joe Clark
brothercake is offline   Reply With Quote
Old 11-19-2003, 01:07 AM   PM User | #3
wac
Regular Coder

 
wac's Avatar
 
Join Date: Sep 2002
Location: Cary, North Carolina, USA
Posts: 357
Thanks: 0
Thanked 0 Times in 0 Posts
wac is an unknown quantity at this point
Well,
The code that I actually want to do is to create a table.
It seems perverse to do
table = document.createElement('TABLE') ;

and then do something like

table.innerHTML = "<tr><td>some stuff</td></tr>" ;

will it work with text node? As in

table.appendChild(document.createTextNode("<tr><td>somestuff</td></tr>"))
;
__________________
Wayne Christian
wac is offline   Reply With Quote
Old 11-19-2003, 01:40 AM   PM User | #4
brothercake
Senior Coder


 
Join Date: Jun 2002
Location: near Oswestry
Posts: 4,509
Thanks: 0
Thanked 0 Times in 0 Posts
brothercake is an unknown quantity at this point
No, createTextNode can only be used to create text nodes, not element nodes (or entities, or comments).

table.innerHTML will work, although I can see why you'd think it perverse. It kinda is perverse to create HTML nodes as a string.

btw - I wouldn't call a table object "table" though - that's just asking for trouble. Call it "myTable" or "theTable" or something.

What you'd want to do to create a table in the DOM is something like this:

var theTable = document.createElement('table');
var tBody = document.createElement('tbody');
var row1 = document.createElement('tr');
var cell1 = document.createElement('td');
text1 = document.createTextNode('some stuff');
theTable.appendChild(tBody);
tBody.appendChild(row1);
row1.appendChild(cell1);
cell1.appendChild(text1);
document.body.appendChild(theTable);

It's long winded I know, but far more powerful and flexible - at each stage of the creation process you can use createAttribute and setAttribute to assign attributes to the nodes, and you also have a reference to each node which you can use later to modify it.

You can also abbreviate it by creating elements directly inside appendChild, like I did with the text node in the previous example, although if you do you won't have a reference to it.
__________________
"Why bother with accessibility? ... Because deep down you know that the web is attractive to people who aren't exactly like you." - Joe Clark

Last edited by brothercake; 11-19-2003 at 01:55 AM..
brothercake is offline   Reply With Quote
Old 11-19-2003, 01:42 AM   PM User | #5
brothercake
Senior Coder


 
Join Date: Jun 2002
Location: near Oswestry
Posts: 4,509
Thanks: 0
Thanked 0 Times in 0 Posts
brothercake is an unknown quantity at this point
[continued .. to save wide spacing in the previous post]

If you're doing a lot of element creation, I'd use something like beetle's createHTMLElement method:
Code:
document.createHTMLElement = function( elemName, attribs )
{
	if ( document.createElementNS )
	{
		var elem = document.createElementNS( "http://www.w3.org/1999/xhtml", elemName );
		var isNamespaced = true;
	} else {
		var elem = document.createElement( elemName );
		var isNamespaced = false;
	}
	if ( typeof attribs != 'undefined' )
	{
		for ( var i in attribs )
		{
			switch ( true )
			{
				case ( i == 'text' )  : elem.appendChild( document.createTextNode( attribs[i] ) ); break;
				case ( i == 'class' ) : elem.className = attribs[i]; break;
				default : 
					if ( isNamespaced )
					{
						elem.setAttributeNS( "http://www.w3.org/1999/xhtml", i, '' );
					} else {
						elem.setAttribute( i, '' );
					}
					elem[i] = attribs[i];
			}
		}
	}
	return elem;
}
Which is double useful because you can create groups of attributes and text nodes as object literals and then pass them to the function, which saves a lot of code:

var attributes = { 'id' : 'foo', 'class' : 'bar', 'text' : 'hello world' };
var myDiv = document.createHTMLElement('div',attributes);

And also because it detects support for XML DOM methods - createElementNS and createAttributeNS - so it continues to work within XHTML served as XML

I use this function a lot .. although I actually use a modified version of it, because of two problems I found (maybe beetle or someone else can confirm or refute these)

- setAttrributeNS is not reliable in mozilla - sometimes it just doesn't work, for no (apparent) reason. However setAttribute continues to work in mozilla even in the XML DOM, so I use that exclusively

- the switch statement causes a crash bug in netscape 4.03

What I'm actually using looks like this:
Code:
//create element and attributes method by beetle (http://www.peterbailey.net/)
//modified by brothercake where commented
document.createHTMLElement = function(elemName,attribs)
{
	var elem = (typeof document.createElementNS != 'undefined') ? document.createElementNS('http://www.w3.org/1999/xhtml',elemName) : document.createElement(elemName);
	if(typeof attribs != 'undefined')
	{
		for(var i in attribs)
		{
			//doing this as a switch statement causes a crash bug in netscape 4
			if(i == 'text')
			{
				elem.appendChild(document.createTextNode(attribs[i])); 
			}
			else if(i == 'class')
			{
				elem.className = attribs[i];
			}
			else
			{
				//there should be a setAttribute|setAttributeNS discriminator here
				//but setAttributeNS doesn't seem to work reliably in mozilla
				//while setAttribute does, even in the XML DOM
				elem.setAttribute(i,attribs[i]);
			}
		}
	}
	return elem;
}
__________________
"Why bother with accessibility? ... Because deep down you know that the web is attractive to people who aren't exactly like you." - Joe Clark

Last edited by brothercake; 11-19-2003 at 01:54 AM..
brothercake is offline   Reply With Quote
Old 11-19-2003, 02:12 AM   PM User | #6
liorean
The thread killer


 
Join Date: Feb 2003
Location: Umeå, Sweden
Posts: 5,575
Thanks: 0
Thanked 84 Times in 75 Posts
liorean will become famous soon enough
Re: How does one add things to documentFragment

Quote:
Originally posted by wac
I also don't see any methods for document fragment in the W3C DOM docs.
[- - -]
From what I saw in the W3C docs there didn't seem to be anyway to populate a document fragment with anything other than to use the standard methods on Node. So why would anyone bother with DocumentFragment when they can do the same thing with Node ???
You're right about that, DocumentFragment specifies nothing in addition to the Node interface.
Quote:
Specified in [DOM2Core]:
interface DocumentFragment : Node {
};
However, there is a large difference between the Node interface and the DocumentFragment interface. The DocumentFragment interface is never inserted into a Node through the DOM, rather, all it's children are inserted directly into the place where the DocumenFragment would have been inserted, had it behaved like a Node. It thus allows insertion of multiple children in order at any point using the regular Node handling methods instead of requiring specific methods.

As for the creation of the DocumentFragment contents, the spec doesn't supply any other means than those of the Node interface. However, using ActiveXObject("XMLDOM") in iew, DOMParser in moz, and various ways in [DOM3LS] you can do it, as well as using the proprietary write method. In ie you can use innerHTML and outerHTML for achieving the same effect. Note that these functions will normalise the output to whatever they feel is most appropriate; so you can't for example write the opening tag in one method call/property assignment, and write the closing tag in another method call/property assignment.


Moz:
<http://unstable.elemental.com/mozill...DOMParser.html>
<http://www.mozilla.org/xmlextras/>

W3C:
<http://www.w3.org/TR/DOM-Level-3-LS/....html#contents>
__________________
liorean <[lio@wg]>
Articles: RegEx evolt wsabstract , Named Arguments
Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards
liorean is offline   Reply With Quote
Old 11-19-2003, 02:48 AM   PM User | #7
liorean
The thread killer


 
Join Date: Feb 2003
Location: Umeå, Sweden
Posts: 5,575
Thanks: 0
Thanked 84 Times in 75 Posts
liorean will become famous soon enough
Quote:
Originally posted by brothercake
- setAttrributeNS is not reliable in mozilla - sometimes it just doesn't work, for no (apparent) reason. However setAttribute continues to work in mozilla even in the XML DOM, so I use that exclusively
It's one of the finer points of XML, really. Attributes without a specified namespace belongs to no namespace (no, they do in fact NOT belong to the default namespace, counter to what one would think), and for a namespaced attribute to be valid toward a DTD, it has to be specified with the given namespace in the attribute declaration. Thus, in most cases you do actually not want an attribute from a namespace; in XHTML in particular you will experience this.
__________________
liorean <[lio@wg]>
Articles: RegEx evolt wsabstract , Named Arguments
Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards
liorean is offline   Reply With Quote
Old 11-19-2003, 01:48 PM   PM User | #8
jkd
Super Moderator


 
jkd's Avatar
 
Join Date: May 2002
Location: metro DC
Posts: 3,168
Thanks: 1
Thanked 18 Times in 18 Posts
jkd will become famous soon enough
The only namespaced attributes you'll probably ever run into are xlink: attributes and xmlns: attributes. Like liorean said, everything else has no namespace.
jkd is offline   Reply With Quote
Old 11-20-2003, 12:34 PM   PM User | #9
brothercake
Senior Coder


 
Join Date: Jun 2002
Location: near Oswestry
Posts: 4,509
Thanks: 0
Thanked 0 Times in 0 Posts
brothercake is an unknown quantity at this point
Oh right, so you can't just willy-nilly create a namespaced attribute if what you're creating isn't a namespaced attribute.
__________________
"Why bother with accessibility? ... Because deep down you know that the web is attractive to people who aren't exactly like you." - Joe Clark
brothercake is offline   Reply With Quote
Old 11-20-2003, 10:03 PM   PM User | #10
beetle
Senior Coder

 
Join Date: Aug 2002
Posts: 3,467
Thanks: 0
Thanked 0 Times in 0 Posts
beetle has a little shameless behaviour in the past
Hey brothercake -- I wonder if it's the nature of the switch that causes NS4 to foul up. Now that I look at it, I'm not sure why I did this using switch( true ) instead of switch( i )
Code:
switch ( i )
{
    case 'text'   : elem.appendChild( document.createTextNode( attribs[i] ) ); break;
    case 'class'  : elem.className = attribs[i]; break;
    default : 
        if ( isNamespaced )
        {
            elem.setAttributeNS( "http://www.w3.org/1999/xhtml", i, '' );
        } else {
            elem.setAttribute( i, '' );
        }
        elem[i] = attribs[i];
}
Glad you found my method useful =)

On occasion, I have to add an additional case, such as for/htmlFor, but those times are pretty rare.
__________________
My Site | fValidate | My Brainbench | MSDN | Gecko | xBrowser DOM | PHP | Ars | PVP
“Minds are like parachutes. They don't work unless they are open”
“Maturity is simply knowing when to not be immature”
beetle is offline   Reply With Quote
Old 11-23-2003, 04:49 PM   PM User | #11
brothercake
Senior Coder


 
Join Date: Jun 2002
Location: near Oswestry
Posts: 4,509
Thanks: 0
Thanked 0 Times in 0 Posts
brothercake is an unknown quantity at this point
Yeah it's dead useful mate

And it is that switch notation that crashes n4.7 - I hadn't actually noticed the unusual notation, but anyway it's fine with switch(i)

Still not convinced about that setAttributeNS though - going on what liorean said it should be testing for whether the attribute actually is a namespaced attribute, rather than whether it can be created as one; which presumably means a double test for support and necessity, something like
Code:
if (isNamespaced && attribs[i].indexOf(':') !=-1)
But what's up with "for"? It rings a bell you mentioning that but I can't remember how it turned out - can you not simply createAttribute("for","whatever") ?
__________________
"Why bother with accessibility? ... Because deep down you know that the web is attractive to people who aren't exactly like you." - Joe Clark

Last edited by brothercake; 11-23-2003 at 05:08 PM..
brothercake is offline   Reply With Quote
Old 11-23-2003, 06:49 PM   PM User | #12
liorean
The thread killer


 
Join Date: Feb 2003
Location: Umeå, Sweden
Posts: 5,575
Thanks: 0
Thanked 84 Times in 75 Posts
liorean will become famous soon enough
In moz and op7 (and likely saf), I believe that you can. However, iew and possibly iem doesn't handle it. This because iew does a hack of it and maps [object DOMHTMLElement].setAttribute([string AttributeName], [string AttributeValue]) to [object DOMHTMLElement][[string AttributeName]] = [string AttributeValue]; which is in turn internally converted to [object DOMHTMLElement].AttributeName = [string AttributeValue], which is illegal for the strings 'for' and 'class', for instance.
__________________
liorean <[lio@wg]>
Articles: RegEx evolt wsabstract , Named Arguments
Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards
liorean is offline   Reply With Quote
Old 11-23-2003, 06:55 PM   PM User | #13
beetle
Senior Coder

 
Join Date: Aug 2002
Posts: 3,467
Thanks: 0
Thanked 0 Times in 0 Posts
beetle has a little shameless behaviour in the past
Ya, what he said
__________________
My Site | fValidate | My Brainbench | MSDN | Gecko | xBrowser DOM | PHP | Ars | PVP
“Minds are like parachutes. They don't work unless they are open”
“Maturity is simply knowing when to not be immature”
beetle is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 06:05 PM.

Home - Contact Us - Archives - Link to CF - Resources - Top 

Powered by vBulletin® Version 3.8.2
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.