jQuery: Traversing

This entry is part 24 of 33 in the series jQuery Tutorial

With selectors, you can pin point a particular html element.

Once an element is targeted, you can traverse around the element using the 3 relationships – Parents, children and sibblings.

jQuery provides a rang of methods to traverse or move around an element.

Below, we look at the .parent() method.

<!doctype html>
<html>
<head>
    <title>parent demo</title>
    <script src='//code.jquery.com/jquery-1.10.2.js'></script>
</head>
<body>

<div><p>Hello</p></div>
<div class='selected'><p>Hello Again</p></div>

<script>
    $('p').parent('.selected').css('background', 'yellow');
</script>

</body>
</html>

Try The Code

We could explain this line:

$('p').parent('.selected').css('background', 'yellow');

It looks for a <p> element and its parent has a class=’selected’.  The statement will traverse around the html elements and look for a match.

There is only one <p> tag in the above example.  The same would go for multiple <p> tags.  Only <p> with a parent of class=’selected’ will be selected in the following example.

<!doctype html>
<html>
<head>
    <title>parent demo</title>
    <script src='//code.jquery.com/jquery-1.10.2.js'></script>
</head>
<body>

<div class='sel'><p>Hello</p></div>
<div class='selected'><p>Hello My Friend.</p>

    <p>Hello 2</p>

    <p>Hello 3</p></div>

<script>
    $('p').parent('.selected').css('background', 'yellow');
</script>

</body>
</html>

Try The Code

Series Navigation<< jQuery: slideToggle effect
jQuery: children >>