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


Click a paragraph to convert it from html to text.

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>html demo</title>
<style>
p {
margin: 8px;
font-size: 20px;
color: blue;
cursor: pointer;
}
b {
text-decoration: underline;
}
button {
cursor: pointer;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>
<b>Click</b> to change the <span id="tag">html</span>
</p>
<p>
to a <span id="text">text</span> node.
</p>
<p>
This <button name="nada">button</button> does nothing.
</p>
<script>
$( "p" ).click(function() {
var htmlString = $( this ).html();
$( this ).text( htmlString );
});
</script>
</body>
</html>

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

Add some html to each div.

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>html demo</title>
<style>
.red {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<span>Hello</span>
<div></div>
<div></div>
<div></div>
<script>
$( "div" ).html( "<span class='red'>Hello <b>Again</b></span>" );
</script>
</body>
</html>

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

Add some html to each div then immediately do further manipulations to the inserted html.

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>html demo</title>
<style>
div {
color: blue;
font-size: 18px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<script>
$( "div" ).html( "<b>Wow!</b> Such excitement..." );
$( "div b" )
.append( document.createTextNode( "!!!" ) )
.css( "color", "red" );
</script>
</body>
</html>

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