通过在 JavaScript 中使用正文标签的 ID 向 <p> 标签添加文本

Add text to a <p> tag by using the ID of the body tag in JavaScript

本文关键字:标签 文本 添加 ID JavaScript 正文      更新时间:2024-01-09

我想在段落中插入一些文本标记,但此处的段落标签没有 ID。因此,使用正文标签的 ID 我想插入文本。我该怎么做?

以下是我的 HTML 代码:

<html>
    <head xmlns="http://www.w3.org/1999/xhtml">
        <meta http-equiv="X-UA-Compatible" content="IE=7">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body dir="ltr" id="tinymce" class="mceContentBody " contenteditable="true">
        <p><br data-mce-bogus="1"></p>
    </body>
</html>

现在,我想在 p 标签中使用 JavaScript 添加文本。

我希望该文本来自另一个变量。使用jQuery可以吗?

JavaScript 解决方案:在第一个p标记中添加文本。

 document.getElementsByTagName("p")[0].innerHTML="Whatever text!";

片段:

var list = document.getElementsByTagName("p")[0].innerHTML="Whatever text!";
//alert(list);
<html>
<head xmlns="http://www.w3.org/1999/xhtml">
  <meta http-equiv="X-UA-Compatible" content="IE=7">
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body dir="ltr" id="tinymce" class="mceContentBody " contenteditable="true">
  <p>
    <br data-mce-bogus="1">
  </p>
</body>
</html>

使用 find 方法查找子项...

(function(){
    $("#tinymce").find("p").html("asd");
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<body dir="ltr" id="tinymce" class="mceContentBody " contenteditable="true">
<p><br data-mce-bogus="1"></p>
</body>

您可以使用直接子选择器 > ,以及body选择器来定位<p>元素:

$("body > p").text("new text");

此外,如果整个 HTML 文档中只有一个 <p> 元素,则可以直接使用 tagname 选择器:

 $("p").text("new text");

添加到 Ani Menon 的答案中,同一解决方案的 jQuery 版本将通过在 jQuery 中使用:first-of-type选择器来实现

$(document).ready(function() {
  $("p:first-of-type").html("something");
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<p></p>

document.querySelectorAll("p")[0].innerHTML = 'success';
document.querySelectorAll("p)[1].innerHTML = 'another success';

索引 0 和 1 表示为 []。用于定位每个段落标签,我的建议仅对一个 p 标签使用此方法......

<html lang="en-US">
<head>
<title>Example JS add text to p</title>
</head>
<body>
<p></p>
<p></p>
</body>
</html>

试试这个

$("p").html("Write Your Text");

试试这个

 $("body > p").text("YourText");

$("body > p").text("YourText");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="X-UA-Compatible" content="IE=7">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body dir="ltr" id="tinymce" class="mceContentBody " contenteditable="true">
<p><br data-mce-bogus="1"></p>
</body>
</html>