Get paragraph text inside an element

2019-03-17 05:09发布

I want to have the text value from a <p> inside a <li> element.

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"];
}

How to do this?

8条回答
时光不老,我们不散
2楼-- · 2019-03-17 05:18

If you use eg. "id" you can do it this way:

   (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>

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-03-17 05:19
<!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>

Here, we can get the text content of h4 by using:

document.getElementById('content').textContent
查看更多
\"骚年 ilove
4楼-- · 2019-03-17 05:23

Use jQuery:

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

should work.

查看更多
乱世女痞
5楼-- · 2019-03-17 05:35

Alternatively, you can also pass the li element itself to your myfunction function as shown:

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

and in your HTML, <li onclick="myfunction(this)">

查看更多
smile是对你的礼貌
6楼-- · 2019-03-17 05:36

change your html to the following:

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

then you can get the content of your paragraph with the following function:

function getContent() {
    return document.getElementById("myParagraph").innerHTML;
}
查看更多
萌系小妹纸
7楼-- · 2019-03-17 05:39

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;
}​
查看更多
登录 后发表回答