Selecting element from DOM with JavaScript and XPath

Viewed 58834

I'm trying to figure out how to select the textarea in the code below using xpath and JavaScript (which is the only option here).

<body>
    <div id="calculator">
        <div id="calculatorController">
            <form action="#" method="get" onsubmit="return false">
                <p>
                    <textarea disabled="disabled"></textarea>
                </p>
            </form>
        ...

I'm trying to do something like this

var element = document.evaluate( '//body/form/p/textarea' ,document, null, XPathResult.ANY_TYPE, null );
// and write back
element.value = "Hello textarea";

But it fails

Anyone keen to help?

Thanks

Update below this

============================================================

The entire block of code looks like this. Don't forget the window.onload=function()

<html>
<head>
  <script type='text/javascript'> 
  //<![CDATA[ 
  window.onload=function(){
  var element = document.evaluate( '//body//form/p/textarea' ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;

        if (element != null) {
            element.value = 'Hello textarea';
        }

  }
  //]]> 
  </script> 
</head>
<body>
    <div id="calculator">
        <div id="calculatorController">
            <form action="#" method="get" onsubmit="return false">
                <p>
                    <textarea disabled="disabled"></textarea>
                </p>
            </form>
        </div>
    </div>
</body>
</html>
2 Answers
Related