Search code examples
javascriptxpathjavascript-injection

JavaScript : injecting ID attribute to an <input> tag by XPATH


I'm trying to automate something using selenium, issue is that the tag has no ID, so I'm finding the control using xpath and JS as so:

document.evaluate('/html/body/header[2]/div[2]/div/div[1]/div[1]/div/div/div/form/fieldset/div[1]/input', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue

and this is the response from chrome's console:

<input> type="file" data-autosubmitoff="true" accept=".xls,.csv,.xlsx" name="File" class="hidden"></input>

which means it found my control by xpath, now I want to inject an ID so that I can refer to it from selenium.

I tried to do it like this:

document.evaluate('/html/body/header[2]/div[2]/div/div[1]/div[1]/div/div/div/form/fieldset/div[1]/input', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.innerHTML='input id="UploadedFileFilter" type="file" data-autosubmitoff="true" accept=".xls,.csv,.xlsx" name="File" class="hidden">'

basically rewriting the whole tag with the ID in it and the console responds accordingly with this answer:

input id="UploadedFileFilter" type="file" data-autosubmitoff="true" accept=".xls,.csv,.xlsx" name="File" class="hidden">"

PERFECT! but when I look in the DOM the Input tag is still the old one, what am I getting wrong?

Thanks.


Solution

  • Instead of editing the HTML directly try just setting the id value like this:

    var path = '/html/body/header[2]/div[2]/div/div[1]/div[1]/div/div/div/form/fieldset/div[1]/input';
    var element = document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
    element.id = 'UploadedFileFilter';
    

    It's also worth noting that innerHTML is the HTML contained within the element. To edit the HTML of the element itself you may be able to use outerHTML.