JQuery selectors are a great way to retrieve content form a page and manipulate the DOM. Its is far more easy to use than using plain browser DOM.
First lets see how to use JQuery selectors to retrieve content from a page and manipulate it.
Examples
<!DOCTYPE html >
<html>
<head>
<title>Document</title>
<script type="text/javascript" src="Scripts/jquery-1.11.3.js"></script>
<script >
$("document").ready(function(){
//Your jquery code run when document is ready
});
</script>
<style type="text/css">
.a { color: Navy; }
.b { color: Maroon; }
</style>
</head>
<body>
<ul id="list1">
<li class="a">item 1</li>
<li class="a">item 2</li>
<li class="b">item 3</li>
<li class="b">item 4</li>
</ul>
<p class="a">This is paragraph 1</p>
<p>This is paragraph 2</p>
<p class="b">This is paragraph 3</p>
<p>This is paragraph 4</p>
</body>
</html>
This is the code for the html file
In this tutorial we select the elements and put a red border around that element. lets see how to select elements with JQuery. Test following select methods by using codes in place where"Your jquery code run when document is ready" comment appears.
- Get elements by type
$("p").css("border","3px solid red");
This will get all elements type of "p" that is paragraph elements and put a red border around it. -
Get elements by ID name
$("#list1").css("border","3px solid red");
This will get all elements that has ID of "list1" and put a red border around it -
Get elements by class attribute
$(".a").css("border","3px solid red");
This will get all elements that has class name "a" and put a red border around it. -
Get one type type of elements which has a particular class name
$("p.b").css("border","3px solid red");
this will get all the paragraph elements which has class attribute of "b".
NOTE:
You need to make sure that you have given correct path to your jquery.js file
Here is a more comprehensive list of JQuery selectors
Selectors and their uses.
- tagname - Finds all elements that have type "tagname"
- #identified - Finds all elements that have ID of "identifier"
- .className - Finds all elements that have a class attribute of "className"
- tag.className - Finds all elements that have the type "tag" and a class attribute of "className"
- tag#id.className - Finds all elements type of "tag" that has ID of "id" and a class attribute of "className"
- * - Finds all the elements on the page
please add a comment if you have any questions or some thing to add to this post
No comments:
Post a Comment