View Full Version : createElement problems

03-09-2005, 05:08 AM
Beyond form validation my javascript skills are slightly lacking, so I've run into a problem trying to implement a simple collapsable box.

var linkNum = 0;

function add( parent_element, child_element ){
var parent = document.getElementById(parent_element);
var child = document.getElementById(child_element);
var link = document.createElement("a");
link.id = "collapse_link_"+linkNum;
link.href = "javascript:collapse(this.id,'"+child_element+"')";

function collapse( link_id, child_id ){
var child = document.getElementById(child_id);
var link = document.getElementById(link_id);
if( child.style.display == "none" ){
child.style.display = "block";
child.style.display = "none";

add( "some_parent", "some_parent_collapsable" );

Given the ID of a parent and child DIV the script first creates an ANCHOR and then handles requests from to collapse or expand the child DIV element. Now the problem I have is, setting the text for the link. But I can't even seem to get a handle to it so I can't change the text.

Reason for dynamically creating the element is so users on older browsers won't even see it. I don't doubt there will be some intersection that loses out, where the browser can expand/collapse but can't write the element so misses out sort of needlessly...but I don't care for them, they miss out. But they won't even know they're missing out.

[edit:] For some reason link_id in collapse() contains link.href instead of link.id

03-09-2005, 07:07 AM
Putting + link.id + in the href assignment, instead of this.id might help... ('this' could be a ref to 'window').

What is the typeof 'link_id' (or link)? An anchor may show up as its href when you alert it--even though its the object itself...

03-09-2005, 07:41 AM
Ahh you are correct. It is right, it was just alert()ing the href. Ok. So now how do I change the text?

03-09-2005, 08:09 AM
link.innerHTML may do...

03-09-2005, 08:10 AM
So now how do I change the text?
Is this what you want?

link.firstChild.nodeValue = (link.firstChild.nodeValue == '-') ? '+' : '-';

I suggest you call collapse() onclick rather than in href.

link.href = "#";
link.onclick = function(){collapse(this.id, child_element); return false;}; //this.id now refers to the current link object

03-09-2005, 01:31 PM
Ahh ok, I had actually contemplated that perhaps onclick was better. And in fact I was planning on doing it like that but I did href instead.

It's working now. Thanks guys.

03-09-2005, 04:04 PM
hm... nodeValue is recomanded as a readonly attribute, would'nt be data a better choise?