Selecting element from DOM with JavaScript and XPath

前端 未结 2 1033
无人共我
无人共我 2020-12-24 07:46

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


    
2条回答
  •  没有蜡笔的小新
    2020-12-24 08:14

    @Mark Robinson comment is right, your Xpath expression is wrong, you could use one of those :

    //body/div/div/form/p/textarea (Mark's example)
    //body//form/p/textarea (any form in body)
    

    Plus, the evaluate function will return a XPathResult object, not the textarea, so you can't do directly element.value

    Here is your example fixed:

    
        

    --

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

提交回复
热议问题