Home Tutorial Jquery Selecting element using jQuery.

 
 

Share on Google+Share on Google+
Selecting element using jQuery.
Posted on: July 26, 2010 at 12:00 AM
Advertisement
In this tutorial , we will discuss about the different methods to select elements of html page.

Selecting element using jQuery

In this tutorial , we will discuss about the different methods to select elements of html page. The jQuery has two ways to select elements. The first uses a combination of CSS and XPath selectors passed as a string to the jQuery constructor (eg. $("div > ul a")). The second uses several methods of the jQuery object. Both approaches can be combined.

For example ,we want to select a list which has an ID "orderedlist" in the given html code. We can do it by two different  ways :

First , by highlighting background color of the text, using following code lines (custom.js) :

$(document).ready(function() {
$("#orderedlist").addClass("red");
});

Above code highlight the text background area by "red" color .The code below is used to highlight the text color to blue :

$(document).ready(function() {
$("#orderedlist > li").addClass("blue");
});

In Second way, when you hover the mouse on text, the text color changes to green to show selection. The code  for this is(custom.js) :

$(document).ready(function() {
$("#orderedlist li:last").hover(function() {
$(this).addClass("green");
},function(){
$(this).removeClass("green");
});
});

The html file code :

<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="jquery-1.4.2.js" type="text/javascript"></script>
<script src="custom.js" type="text/javascript"></script>
</head>
<body>
<h1>jQuery selector example</h1>
<h3>
<ol id="orderedlist">
<li>First element</li>
<li>Second element</li>
<li>Third element</li>
</ol></h3>
<p>When you hover mouse on third element ,it's color changes to green to show selection</p>
</body>
</html>

style.css

ol, li{
margin: 0;
padding: 0;
}
li { margin-left: 20px; }

.red { background-color: red; }
.blue { color: blue; }
.green { color: green; }


hover {
background-color: #fc7;
}

OUTPUT :

Output when highlighting background color to red :

 

Output when highlighting text color to blue :

 

 

Output when mouse hover changes color of text to green :

 

Download Source Code

Click here to see demo

Advertisement

Related Tags for Selecting element using jQuery.:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 26, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com