Wednesday, October 01, 2008

jQuery child selector usage example


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" charset="utf-8" src="/lib/jquery/jquery-1.2.6.js"></script>
<style type="text/css" media="screen">
.green {
color: green;
}
.last {
background-color: #ddd;
}
div {
margin: 2px;
border: #eee 1px solid;
}
table, td {
width: 100%;
border: #ddd 1px solid;
}
</style>
</head>
<body>
<div>
<span>John,</span>
<span>Karl,</span>
<span>Brandon</span>
</div>
<div>
<span>Glen,</span>
<span>Tane,</span>
<span>Ralph</span>
</div>
<div>
<button>Sibling!</button>
<button>Sibling!</button>
</div>

<div>
<button>Sibling!</button>
</div>
<div>
None
</div>

<div>
<button>Sibling!</button>
<button>Sibling!</button>
<button>Sibling!</button>
</div>

<div>
<button>Sibling!</button>
</div>

<div>
<ul>
<li>John</li>
<li>Karl</li>
<li>Brandon</li>
</ul>
</div>

<div>
<ul>
<li>Sam</li>
</ul>
</div>

<div>
<ul>
<li>Glen</li>
<li>Tane</li>
<li>Ralph</li>
<li>David</li>
</ul>
</div>

<div class="buttons">
<button>:nth-child(even)</button>
<button>:nth-child(odd)</button>
<button>:nth-child(3n)</button>
<button>:nth-child(2)</button>
</div>
<div class="buttons">
<button>:nth-child(3n+1)</button>
<button>:nth-child(3n+2)</button>
<button>:even</button>
<button>:odd</button>
</div>
<div>
<table>
<tr><td>John</td></tr>
<tr><td>Karl</td></tr>
<tr><td>Brandon</td></tr>
<tr><td>Benjamin</td></tr>
</table>
</div>
<div>
<table>
<tr><td>Sam</td></tr>
</table>
</div>
<div>
<table>
<tr><td>Glen</td></tr>
<tr><td>Tane</td></tr>
<tr><td>Ralph</td></tr>
<tr><td>David</td></tr>
<tr><td>Mike</td></tr>
<tr><td>Dan</td></tr>
</table>
</div>
<span>
tr<span id="inner"></span>
</span>

<script type="text/javascript" charset="utf-8">
// Matches the first child of its parent.
$("div span:first-child")
.css("text-decoration", "underline")
.hover(function () {
$(this).addClass("green");
}, function () {
$(this).removeClass("green");
});

$("div span:last-child")
.css({color: "red", fontSize: "80%"})
.hover(function () {
$(this).addClass("last");
}, function () {
$(this).removeClass("last");
});

$("div button:only-child").text("Alone Button in Div");
$("ul li:nth-child(2)").append("<span> - 2nd!</span>");

$("div.buttons button").click(function () {
console.log(this);
var str = $(this).text();
$("tr").css("background", "white");
$("tr" + str).css("background", "#f98");
$("#inner").text(str);
});
</script>
</body>
</html>

No comments :