HTML and CSS Reference
In-Depth Information
Don't forget to prefix the iD with “#”. Because the querySelector() function can be used with any
type of selector, you'll need the hash symbol to indicate this is an iD selector.
Run the web page using Chrome (or Safari) and verify the range control still works.
Using querySelectorAll
That was a fairly trivial example so now I'll demonstrate a more complex selector. You'll add a JavaScript function
that will change the color on all of the internal links in the nav element. Arguably you could just do this in the
style sheet but there are times when you need to do it in code as well. For example, you might need to change the
style programmatically based on user input.
Add the following function to the script element in the Default.cshtml page:
function adjustInternalLinks(){
var links=document.querySelectorAll("nav ul li a[href ^='#']");
for (var i=0; i<links.length; i++){
The CSS selector is nav ul li a[href ^='#'] , which returns all a elements with an href attribute that
begins with the # character. This is further filtered to only elements that have the nav , ul , and li parentage. This
will exclude links that may appear in other sections.
The querySelectorAll() function returns an array so this code iterates through the array making each
element green. Now you'll need to call this function. Add the code shown in bold to the body element:
<body onload="adjustInternalLinks()" >
This will call the function when the page is loaded but you could just as easily call this based on some
appropriate user input to make the style dynamic. Save the changes and reload the page. You should now have
green links. Note that the link to is not green because it is an external link and doesn't start
with “#”.
Creating the Visual Studio Project
For the rest of the exercises in this chapter you'll use a Visual Studio project. You'll create an empty web site now
and then add features to it later. Start Visual Studio 2012 and select the New Project link. Select the MVC4 project
template and enter Chapter 5 for the name as shown in Figure 5-1 .
Search WWH ::

Custom Search