Share via


Getting Started on Line-of-Business HTML5 App – Part 6 Selecting HTML with JQuery

imageAccording to its Website, “JQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript. ” And it is true.

jQuery makes it possible for your code to get an HTML element and do something cool with it. In the example, I’ll show how you can show and hide sections inside your page. But there are plenty more things you can do.

About jQuery

jQuery is a lightweight open source JavaScript library (only 15kb in size) that in a relatively short span of time has become one of the most popular libraries on the web.

In the past you would have needed to write something like this to access a value from a radio button in a group named someRadioGroup.

 var checkedValue;

var elements = document.getElementsByTagName('input');

for (var n = 0; n < elements.length; n++) {

    if (elements[n].type == 'radio' &&
        element[n].name == 'someRadioGroup' && 
        elements[n] == checked {

    checkedValue = elements[n].value;
    }

}

In jQuery:

 var checkedValue = $('[name = "someRadioGroup"]:checked').val();

A big part of the appeal of jQuery is that it allows you to elegantly (and efficiently) find and manipulate HTML elements with minimum lines of code. jQuery supports this via a nice "selector" API that allows developers to query for HTML elements, and then apply "commands" to them. One of the characteristics of jQuery commands is that they can be "chained" together - so that the result of one command can feed into another. jQuery also includes a built-in set of animation APIs that can be used as commands.

In 2008 Scott Guthrie announced that Microsoft would begin offering product support for jQuery, and that we’d be including it in new versions of Visual Studio going forward. By default, when you create new ASP.NET Web Forms and ASP.NET MVC projects you’ll find jQuery automatically added to your project.

So JQuery is include in the Visual Studio 2010 toolset.

And the Visual Studio 11 beta includes jQuery when you create Web projects.

image

And you get Intellisense support when you have the vsdoc.js file included. The vsdoc version of the file allows Visual Studio to use Intellisense for jQuery development. The vsdoc file contains XML annotations, within JavaScript comments, which allow Visual Studio to parse, interpret and provide Intellisense while working with JavaScript files.

image

In this part, I’ll show how you can access particular elements in your HTML and how you can take action on those element. I’ll also provide an introduction into how you can dynamically change the HTML on the fly.

In later parts, I’ll show how you can do two-way data binding using jQuery data templates and how to use jQuery UI to enhance the user experience using widgets and UI templates.

But first, let’s get started with a simple feature. First, we load jQuery.

Load jQuery

First of all, I want to load jQuery. This is done with a bit of script in head, just before I start my own jQuery.

 <!-- Get jQuery from Microsoft CDN and fall back to local if necessary -->
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js " type="text/javascript"></script>    
<script>       
 !window.jQuery && document.write('<script src="js/jquery-1.5.1.min.js"><\/script>')
</script>

Using CSS Selector to Get Access to HTML5

jQuery offers a powerful set of tools for matching a set of elements in a document. jQuery selectors allow you to select and manipulate HTML elements as a group or as a single element by first getting the element or attribute.

What makes jQuery so easy to select elements is its selector engine, Sizzle, and it’s easy syntax, which is based on the same syntax you would use to select elements in CSS by borrowing from CSS 1-3.

Select by ID

In this example, we select some text using the <p> tag’s identifier hello  using a #. And then we get its text and show it in an alert.

 <p id="hello">Hello World</p>  

<script type="text/javascript">  
     //Select the element by it's ID 
     alert($("#hello").text()); // Hello World 
</script> 

Valid HTML requires that each ID be unique on the page. A page is not considered valid if there is more then one of the same ID on the page. Because of this, jQuery will only match the first element that matches that ID on the page.

Class Selector

You can recognize this as a selector of a class:

 $('.reviewinfo')

and then you perform action on the selection.

More Complex Selectors

Let’s start with an example.

If you have this HTML:

 <ul>
    <li><a href="https://jquerymobile.com">jQuery Mobile</a></li>
</ul>
<div>
    <ul>
        <li><a href="https://jquery.com">jQuery</a></li>
        <li><a href="https://jqueryui.com">jQuery UI</a></li>
    </ul>
</div>

And use this selector:

 $("div ul"); 

You will get

 <ul>
    <li><a href="https://jquery.com">jQuery</a></li>
    <li><a href="https://jqueryui.com">jQuery UI</a></li>
</ul>

More Selectors

jQuery selectors are required at every step while using jQuery. Selectors allow you to get the exact element/attribute you want from your HTML document. For example:

  • $("*") selects all elements.
  • $("p") selects all <p> elements.
  • $("p.intro") selects all <p> elements with class="intro".
  • $("p#intro") selects the first <p> elements with id="intro".

In the following example, we get an element and then perform a change in the CSS. And we use the CSS selector

     <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js " type="text/javascript"></script>
    <script>        !window.jQuery && document.write('<script src="js/jquery-1.5.1.min.js"><\/script>')</script>
    <script>
        $(document).ready(function () {
            // we'll put our code here
            alert('page ready');

            // Id selector
            $("#div1").css("backgroundColor", "pink");

            // Class selector
            $(".required").css("border", "dashed 2px red");

            // Element selector
            $("span").css("color", "purple");
        });
        </script>
</head>
<body>
    <div>
    
        <div id="div1">My div with id attribute of div1</div>
        
        <div class="required">Here is the second message</div>

        <span>Here is the third message</span>

    </div>
</body>

NOTE:  jQuery will fail silently if there are no elements that match your selection. There maybe a time when you will want to perform some actions based on if an element is present or not in the DOM. To test for an element we use the length property to test how many elements are in the DOM.

 if ($(“div”).length) {
//do something.
}

Selecting Multiple Elements

Using the CSS selector, you can also use multiple items in your selector such as

 $('p a')

which would return the links (<a> elements) inside of a paragraph (<p> elements). so just as you would describe elements for styling purposes, you can get those items and then take action.

You can also select multiple elements:

 <script>$("div,span,p.myClass").css("border","3px solid red");</script>

Filter Selectors

You can narrow your selection by using filters.

There are three kinds of filter selectors that you can use, numerical or positioned filters:

:first - Matches the first item in the context
:last - Matches the last item in the context
:first-child - Matches the first child item in the context
:last-child - Matches the last child item in the context
:only-child - Returns all items that have no siblings
:nth-child(n) - Matches the nth child item in the context
:nth-child(even|odd) - Matches the even or odd children in the context
:nth-child(xn+y) - Matches the nth children based on the formula. Examples: (3x+1) Get the first element after every third child. (3x) get every third child element.
:even - Match the even children in the context
:odd - Match the odd children in the context
:eq(n) - Match the child at the nth position in the context
:gt(n) - Match the children that are greater then the nth position in the context
:lt(n) - Match the children that are lesser then the nth position in the context

Traditional CSS filters:

:checked - Matches checkbox/radio button elements in checked state
:disabled - Matches disabled elements
:enabled - Matches enabled elements
:not(selector) - Matches elements that are not in the selection

Pseudo Selectors

jQuery also adds additional pseudo selectors to enable you to narrow your selection further. You can find out more about selectors by reviewing the complete reference Selector category on jQuery API site.

:animated - Matches elements that are being animated.
:button - Matches button elements
:checkbox - Matches checkbox elements
:contains(string) - Matches elements that contain specified string (i.e. $(“p:contains(jQuery)”);)
:file - Matches file input elements
:has(selector) - Matches elements that have at least one of the specified matched selector.
:header - Matches header elements. (i.e. h1-h6)
:hidden - Matches hidden elements
:image - Matches image input elements
:input - Matches form elements
:parent - Matches elements that have children, including text, which are not empty
:password - Matches elements of type password
:radio - Matches radio elements
:reset - Matches reset buttons
:selected - Matches option elements in selected state
:submit - Matches elements of type submit
:text - Matches elements of type text
:visible - Matches elements that are visible

Resources

jQuery has some great tutorials on their site.

For more information on selection, see How Do I Use jQuery Selectors?

Next Up

Let’s use jQuery and Modernizr to save some data locally.

Bruce D. KyleISV Architect Evangelist | Microsoft Corporation

image