how to access value of paragraph tag?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rahullko05
    New Member
    • Oct 2008
    • 34

    #1

    how to access value of paragraph tag?

    i need to access the value of paragraph tag using dom in javascript.

    lets say there is <p id="test">this is test para </p>
    now how to access the value inside this para ie. "this is test para"?
    i have tried:
    var text = document.getEle mentById("test" ).value, also tried document.getEle mentById("test" ).firstChild

    but none of them return value of paragraph.

    where as in case of textarea i can access this value inside it by
    document.getEle mentById("someI d").value

    please help me. i need to resolve this very urgently.
    thanks in advance.
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    You need to use the innerHTML property to access stuff in the paragraph.
    For example:
    Code:
    <html>
    <head>
    <script type="text/javascript">
    function showParagraph()
    {
       alert(document.getElementById('test').innerHTML);
    
    }
    </script>
    </head>
    
    <body>
    <p id="test">this is test paragraph</p>
    <input type="button" onclick="showParagraph()" value="show paragraph" />
    </body>
    
    </html>
    Last edited by Frinavale; Feb 20 '14, 04:57 PM.

    Comment

    • Dormilich
      Recognized Expert Expert
      • Aug 2008
      • 8694

      #3
      the DOM-level-1 method is
      Code:
      var para = document.getElementById('test');
      var text = para.firstChild.nodeValue; // will give the first text node's value
      
      // some browsers work with
      var text = para.textContent;
      the value attribute/property is exclusive for form elements.

      Comment

      • mrhoo
        Contributor
        • Jun 2006
        • 428

        #4
        If you only care about the text content of a paragraph you can read it with:
        Code:
        function textvalue(elementreference){
            return elementreference.textContent || elementreference.innerText || '';
        }
        Last edited by Dormilich; May 24 '09, 06:40 AM. Reason: please use [code] tags!

        Comment

        • alexisma
          New Member
          • Feb 2014
          • 1

          #5
          mrhoo.
          Thank you, it worked for me (:

          Comment

          Working...