ptg16476052
546 LESSON 19: Using JavaScript in Your Pages
At the end, the function returns false:
questions = faqList.getElementsByTagName("dt");
for (i = 0; i < questions.length; i++) {
questions[i].onclick = function() {
// The actual event handling code goes here.
}
}
First, I use getElementsByTagName() to get a list of all the <dt> tags that are children of
faqList. Then I use a for loop to iterate over them and bind the function described pre-
viously to their onclick event.
The Same Code with jQuery
Now here’s a look at code that achieves the same results using jQuery. There are some
flaws in the previous code as well that this solution gets around. For example, for reasons
of simplicity and cross-browser compatibility, I specified the click event handler, attach-
ing it directly to the onclick property of the relevant element. I did the same thing with
the body.onload handler. As you know, this approach can interfere with other scripts you
might want to use on the page.
First I load jQuery from the CDN with this line of HTML:
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
Here’s the new faq.js script:
$(function() {
$("#faq dd").hide();
$("#faq dt").click(function(event) {
event.preventDefault();
$(this).next("dd").toggle();
});
});
As you can see, the libraries enable me to accomplish a lot more than I could writing raw
JavaScript with just a few lines of code.
Adding New Content to a Page
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 elements 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.
▼
▲