HTML and CSS Reference
In-Depth Information
selector. The querySelector method returns the first element it finds that matches the selec-
tor criteria passed to it, whereas the querySelectorAll method returns all elements that match
the selector criteria passed in. The elements are still returned in the form of a NodeList object.
Both methods exist not only on the document itself, but also on each element. Therefore,
when you have a reference to an element, you can use these methods to search its children
without having to traverse the entire document. You can see some simpler examples in this
section.
To find all the <p> elements on a page, you can use this syntax:
document.querySelectorAll("p");
To find an element by its unique ID, you can use this syntax:
document.querySelector("#outerDiv");
Put those two lines into your HTML file and try them out. You will explore much more
advanced and interesting functionality in Chapter 4. For now, you can use what you've seen
about finding elements in the DOM to apply that knowledge to adding or modifying the
DOM through code.
EXAM TIP
jQuery is probably the most popular library available to date for simplifying and extending
the core JavaScript capabilities. Although jQuery isn't a Microsoft technology, it's essentially
an industry standard and fully supported by Microsoft. As such, web developers today are
generally understood to have a grasp of using jQuery interchangeably with core JavaScript.
The exam will expect that you can use jQuery effectively in place of the document object
selector methods.
Altering the DOM
Having access to the DOM through JavaScript can be used to provide rich user experience
when creating dynamic webpages. So far, all you've done is obtain references to the elements,
which is not particularly useful by itself. The purpose of retrieving elements from the DOM
is to be able to do something with them. In this section, you look at how to manipulate the
DOM by using JavaScript code to add and remove items.
After you have a reference to a container element, you can add child elements to it
dynamically. You can remove elements from it or simply hide elements. When you remove an
element from the DOM, it is gone. So if you want to make something invisible to the user but
 
 
Search WWH ::




Custom Search