.parent()
In this chapter you will learn:
- Syntax and Description for .parent() method
- How to get parent for a form input submit element
- How to filter parent with clas
- Get parent and do the verification
- How to get the first parent
Syntax and Description
.parent([selector])
gets the parent of each element in the current set of matched elements, optionally
filtered by a selector.
selector (optional)
is a string containing
a selector expression to match elements against.
Its return value is the new jQuery object.
Get parent for a form input element
The following code gets form input parent and then sets the background and border.
<html><!--from j a va 2 s . c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var input = $(":submit").parent().css({background:"yellow", border:"3px red solid"});
$('#result').text('jQuery matched ' + input.length + ' elements.');
});
</script>
</head>
<body>
<form><input type="submit" /></form>
<div id="result"></div>
</body>
</html>
Filter parent with class
The following code gets all parents for a paragraph and then filter parents with certain class.
<html><!--from ja v a 2 s . com-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").parent(".selected").css("background", "yellow");
});
</script>
<style>
.y { background:yellow; }
</style>
</head>
<body>
<body>
<div><span class="selected">java2s.com</p></span>
<span>java2s.com</span>
</div>
</body>
</html>
Verify the parent selection with is() method
The following code gets the parent for a form element and then uses the is() method to check if the parent is a form element.
<html><!--from j a v a 2 s .co m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert( $(":checkbox").parent().is("form"));
});
</script>
</head>
<body>
<body>
<form><input type="checkbox" /></form>
</body>
</html>
Get the first parent
The following code filters the set of parent elements to get the first.
<html><!-- j av a 2 s . c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("*", document.body).each(function () {
var parentTag = $(this).parent().get(0).tagName;
$(this).prepend(document.createTextNode(parentTag + " > "));
});
});
</script>
</head>
<body>
<body>
<p>p</p>
<div>div</div>
<p>p</p>
<p>p</p>
<div>div</div>
<p>p</p>
<div>java2s.com</div>
</body>
</html>
Next chapter...
What you will learn in the next chapter:
- Syntax and Description for .parents()
- Count the parent elements by tag name
- How to map parent elements to get all their names
- Find all unique div parent elements of each span