Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

548 LESSON 19: Using JavaScript in Your Pages


}
this.innerHTML = "Expand All";
}
return false;
};

faq = document.getElementById("faq");
faq.insertBefore(expandAllDiv, faq.firstChild);
}

First , I declare the variables I use in the function, and then I start creating the elements.
The createElement() method of the document object is used to create an element. It
accepts the element name as the argument. I create the <div> element and then call the
setAttribute() method to add the id attribute to that element. The setAttribute()
method takes two arguments: the attribute name and the value for that attribute. Then I
create the link by creating a new <a> element. I set the href attribute to #, because the
event handler for the link’s onclick event will return false anyway, and I add an id for
the link, too. To add the link text, I call the document.createTextNode() method:
expandAllLink.appendChild(document.createTextNode("Expand All"));
I pass the results of that method call to the appendChild() method of expandAllLink,
which results in the text node being placed inside the <a> tag. Then on the next line I
append the link to the <div>, again using appendChild(). The last thing to do before
appending the <div> to an element that’s already on the page (causing it to appear) is to
add the onclick handler to the link.
I’m again attaching the onclick handler using an anonymous function, as I did in the
previous example. In this case, I use the same technique I did in the previous example,
obtaining a reference to the <div> with the ID faq and then retrieving a list of <dd> ele-
ments inside it.
At that point, I inspect the contents of this.innerHTML. In an event handler, this is a
reference to the element upon which the event was called, so in this case, it’s the link.
The innerHTML property contains whatever is inside that element—in this case, the link
text. If the link text is “Expand All,” I iterate over each of the answers and set their
display property to block. Then I modify the this.innerHTML to read "Collapse All".
That changes the link text to Collapse All, which not only alters the display but causes
the same function to hide all the answers when the user clicks on the link again. Then the
function returns false so that the link itself is not processed.
Once the onclick handler is set up, I add the link to the document. I want to insert the
link immediately before the list of frequently asked questions. To do so, I get a reference


Free download pdf