Wednesday, October 01, 2008

jQuery attributes selectors usage example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns="">
<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>
<input name="milkman" />
<input name="letterman2" />
<input name="newmilk" />
<input name="newsletter" />
<input name="jobletter" />
<input name="jobletter2" />
<input id="man-news" name="man-news" />
<input id="letterman" name="new-letterman" />
<input type="radio" name="newsletter" value="Hot Fuzz" />
<input type="radio" name="newsletter" value="Cold Fusion" />
<input type="radio" name="accept" value="Evil Plans" />
<div>no id</div>
<div id="hey">with id</div>
<div id="there">has an id</div>
<div>no id</div>

<script type="text/javascript" charset="utf-8">
// $("input[@name*='man']").val("has man in it!"); // the same below using XPath
$("input[name*='man']").val("has man in it!"); // attributeContains( String attribute, String value )
$("input[name^='news']").val("news here!");
$("input[name$='letter']").val("a letter"); // attributeEndsWith( String attribute, String value )
$("input[name='newsletter']").next().text(" is newsletter");
$("input[name!='newsletter']").next().text(" is not newsletter");

// one() function, The handler is executed only once for each element
$("div[id]").one("click", function(){
var idString = $(this).text() + " = " + $(this).attr("id");

$("input[id][name$='man']").val("only this one"); // Matches elements that have the specified attribute and it contains a certain value.

No comments :