获取元素中的段落文本

Get paragraph text inside an element

本文关键字:段落 文本 元素 获取      更新时间:2024-01-22

我希望<p>中的文本值位于<li>元素中。

html

<ul>
  <li onclick="myfunction()">
    <span></span>
    <p>This Text</p>
  </li>
</ul>

javascript:

function myfunction() {
  var TextInsideLi = [the result of this has to be the text inside the paragraph"];
}

如何做到这一点?

或者,您也可以将li元素本身传递给myfunction函数,如图所示:

function myfunction(ctrl) {
  var TextInsideLi = ctrl.getElementsByTagName('p')[0].innerHTML;
}

在您的HTML中,<li onclick="myfunction(this)">

您使用jQuery吗?是一个不错的选择

text = $('p').text();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Where to JavaScript</title>
    <!-- JavaScript in head tag-->
    <script>
        function changeHtmlContent() {
            var content = document.getElementById('content').textContent;
            alert(content);
        }
    </script>
</head>
<body>
    <h4 id="content">Welcome to JavaScript!</h4>
    <button onclick="changeHtmlContent()">Change the content</button>
</body>

在这里,我们可以使用:获取h4的文本内容

document.getElementById('content').textContent

试试这个:

<li onclick="myfunction(this)">
function myfunction(li) {
    var TextInsideLi = li.getElementsByTagName('p')[0].innerHTML;
}

实时演示

将html更改为以下内容:

<ul>
    <li onclick="myfunction()">
        <span></span>
        <p id="myParagraph">This Text</p>
    </li>
</ul>

然后你可以通过以下功能获得你的段落内容:

function getContent() {
    return document.getElementById("myParagraph").innerHTML;
}

HTML

<ul>
  <li onclick="myfunction(this)">
    <span></span>
    <p>This Text</p>
  </li>
</ul>​

JavaScript

function myfunction(foo) {
    var elem = foo.getElementsByTagName('p');
    var TextInsideLi = elem[0].innerHTML;
}​

使用jQuery:

$("li").find("p").html()

应该起作用。

如果你使用e.g."id",你可以这样做:

   (function() {
    let x = document.getElementById("idName");
    let y = document.getElementById("liName");
    
    y.addEventListener('click', function(e) {
        y.appendChild(x);
    });
  
})();
<html lang="en">
<head>
    <title></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <p id="idName">TEXT</p>
    <ul>
        <li id="liName">
        </li>
    </ul>
</body>
<script src="js/scripts/script.js"></script>
</html>

Id属性添加到P标记中,其值类似于文本或其他内容:

function gettext() {
    var amount = document.getElementById('text').value;
}
const copyLink = () => {
   console.log('btn click');
   let linkURL = document.getElementById('clipboard').innerText;
}

在p标签中:

<p id="clipboard" class="px-1 sm:px-8 py-4 ">
    {`https://offerstreet.in/coupons/coupon/?asin=${asin}`} 
</p>