在 jQuery 中将 H1 元素及其文本放置在特定索引处

jqueryweb developmentobject oriented programming更新于 2025/8/21 3:37:17

要设置元素及其文本,请使用 jQuery 中的 text() 方法。然后,使用 :nth-child 选择器将其放置在特定位置。以下是代码 −

示例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<h1 class='demo'>JavaScript</h1>
<h1 class='demo'>MySQL</h1>
<h1 class='demo'>MongoDB</h1>
<h1 class='demo'>Java</h1>
<h1 class='demo'>C#</h1>
<script>
   $('h1:nth-child(4)').text("Python");
</script>
</body>
</html>

要运行上述程序,请将文件名保存为"anyName.html(index.html)",然后右键单击该文件。在 VS Code 编辑器中选择"使用实时服务器打开"选项。

输出

这将产生以下输出 −


相关文章