Saturday, September 24, 2011

Tag or Element Selector examples in JQuery

In this post we will understand more about Tag or Element Selector in JQuery.

Continue with our earlier example of JQuery Selector


I have created a sample asp.net web form.
My HTML looks something as below image.
And it appears in browser as under

Now let see, how element selector works with asp.net controls in JQuery.


*Please Note: Asp.net web form which is used for example is not following all best practices, since this tutorial series will be focusing only on Jquery.  It doesn't contains code in .cs file for input real data in DB.

We know that internally when asp.net web page renders,

  • All label controls as span tag 
  • All Textbox control as input tag
  • All dropdown control as select tag
    • All dropdown items as option element
  • And so on... ok, now lets begin the game!


Example 1: Lets highlight all label controls, with yellow background.
Please add below script at the end of the page.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("span").css("background-color", "Yellow");
    });
</script>

It will result in following output on browser screen.


Example 2: Lets give border to all textbox controls, with blue border.
Please add below script at the end of the page.


<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("span").css("background-color", "Yellow");
        $("input:text").css("border-color", "blue");        
    });
</script>


Please note: input element is used for multiple purpose,
<input type="text"/> - will display textbox
<input type="submit"/> - will display button

You might have also notice that multiline textbox is rendered as textarea and that is reason it doesn't have blue border.

Output on browser screen.

We have found that here it is an issue since, we want to give blue border to all textbox, irrespective of whether it is textmode is multiline (i.e. Textarea) or normal single line textbox control (i.e. Input type="text").

I can add one more line for Textarea to achieve this, but it will not be good way to do things from maintainability point of view.  Example: let say if requirement gets change and i want my blue border to appear as red.  There are chances that i update one line and not other, in that case few textbox have blue border and other have red.

Watch Live demo of JQuery Element Selector Example

No comments:

Most Recent Post

Community Updates

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape