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


Запускает поиск всех элементов span во всех параграфах на странице, это аналогично селектору $( "p span" )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>find demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p><span>Привет</span>, как дела?</p>
<p>У меня? Все <span>хорошо</span>.</p>
<script>
$( "p" ).find( "span" ).css( "color", "red" );
</script>
</body>
</html>

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

Выбор все тэгов span при помощи коллекции jQuery. Только span'ы внутри тэга p изменят цвет текста на красный, остальные останутся с голубым цветом текста.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>find demo</title>
<style>
span {
color: blue;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p><span>Привет</span>, как дела?</p>
<p>У меня? Все <span>хорошо</span>.</p>
<div>Ты уже <span>поел</span>?</div>
<script>
var spans = $( "span" );
$( "p" ).find( spans ).css( "color", "red" );
</script>
</body>
</html>

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

Добавляет span'ы вокруг каждого слова и затем добавляет фон при наведении для всех слов и выделение курсовом для слов начинающихся с буквы t.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>find demo</title>
<style>
p {
font-size: 20px;
width: 200px;
color: blue;
font-weight: bold;
margin: 0 10px;
}
.hilite {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>
When the day is short
find that which matters to you
or stop believing
</p>
<script>
var newText = $( "p" ).text().split( " " ).join( "</span> <span>" );
newText = "<span>" + newText + "</span>";
$( "p" )
.html( newText )
.find( "span" )
.hover(function() {
$( this ).addClass( "hilite" );
}, function() {
$( this ).removeClass( "hilite" );
})
.end()
.find( ":contains('t')" )
.css({
"font-style": "italic",
"font-weight": "bolder"
});
</script>
</body>
</html>

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