Get paragraph text inside an element

后端 未结 9 511
孤独总比滥情好
孤独总比滥情好 2021-02-03 19:21

I want to have the text value from a

inside a

  • element.

    html:

  • 相关标签:
    9条回答
    • 2021-02-03 20:03

      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>

      0 讨论(0)
    • 2021-02-03 20:05
      <!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
      
      0 讨论(0)
    • 2021-02-03 20:06

      Add an Id property into the P tag with value like text or something:

      function gettext() {
          var amount = document.getElementById('text').value;
      }
      
      0 讨论(0)
    • 2021-02-03 20:07

      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)">

      0 讨论(0)
    • 2021-02-03 20:11

      Do you use jQuery? A good option would be

      text = $('p').text();
      
      0 讨论(0)
    • 2021-02-03 20:12

      Try this:

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

      Live demo

      0 讨论(0)
    提交回复
    热议问题