HTML and CSS Reference
In-Depth Information
The last example demonstrated how to modify styles on a page. In this example, I
explain how to modify the content on a page using JavaScript. You can create new ele-
ments in JavaScript and then attach them to the document in any location that you
choose. You can also modify elements that are already on the page or remove elements if
you need to do so.
Task:
Exercise 15.3: Add an Expand All/Collapse All Link to
the FAQ
▼
In this example, I add a new feature to the FAQ page presented in the previous example.
In that example, I illustrated how to add new features to a page using JavaScript without
modifying the markup in any way. This example will continue along those lines. I won't
be making any changes at all to the markup on the page; all the changes will take place
inside the JavaScript file.
In this example, I add a link to the page that expands all the questions in the FAQ, or if
all the questions are already expanded, collapses all the questions. The label on the link
will change depending on its behavior, and the function of the link will also change if the
user individually collapses or expands all the questions.
Adding the Link to the Page
Because the link functions only if the user has
JavaScript enabled, I am going to add it dynamically using JavaScript. I've added a new
function to the JavaScript file that takes care of adding the link, which I call from the
onload
handler for the page. The function adds more than just a link to the page. It adds
a link, a
<div>
containing the link, and the
onclick
handler for the link. Here's the func-
tion, which I've named
addExpandAllLink()
:
function addExpandAllLink() {
var expandAllDiv, expandAllLink, faq;
expandAllDiv = document.createElement(“div”);
expandAllDiv.setAttribute(“id”, “expandAll”);
expandAllLink = document.createElement(“a”);
expandAllLink.setAttribute(“href”, “#”);
expandAllLink.setAttribute(“id”, “expandAllLink”);
expandAllLink.appendChild(document.createTextNode(“Expand All”));
expandAllDiv.appendChild(expandAllLink);
expandAllLink.onclick = function() {
var faqList, answers;
faqList = document.getElementById(“faq”);
answers = faqList.getElementsByTagName(“dd”);