Примеры для jQuery()


Find all p elements that are children of a div element and apply a border to them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>one</p>
<div><p>two</p></div>
<p>three</p>
<script>
$( "div > p" ).css( "border", "1px solid gray" );
</script>
</body>
</html>

Демонстрация:

Find all inputs of type radio within the first form in the document.

1
$( "input:radio", document.forms[ 0 ] );

Find all div elements within an XML document from an Ajax response.

1
$( "div", xml.responseXML );

Set the background color of the page to black.

1
$( document.body ).css( "background", "black" );

Hide all the input elements within a form.

1
$( myForm.elements ).hide();

Create a div element (and all of its contents) dynamically and append it to the body element. Internally, an element is created and its innerHTML property set to the given markup.

1
$( "<div><p>Hello</p></div>" ).appendTo( "body" )

Create some DOM elements.

1
2
3
4
5
6
7
8
$( "<div/>", {
"class": "test",
text: "Click me!",
click: function() {
$( this ).toggleClass( "test" );
}
})
.appendTo( "body" );

Execute the function when the DOM is ready to be used.

1
2
3
$(function() {
// Document is ready
});

Use both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias.

1
2
3
jQuery(function( $ ) {
// Your code using failsafe $ alias here...
});