Search code examples
javajavascriptseleniumexecutor

How to append "Input Tags" into the DOM in Runtime Dynamically using Selenium JavascriptExecutor?


I need to append the following element to the DOM in run time(dynamically)..

    <input type="text" name="imagesToAdd" value="3566">

I tried doing it by using Selenium JavascriptExecutor; But it gives an error saying "org.openqa.selenium.WebDriverException: document.getElementById(...).append is not a function"

((JavascriptExecutor) driver).executeAsyncScript("document.getElementById('post-ad_title').append('<input type=\"text\" name=\"imagesToAdd\"value=\"3566\">')");

Solution

  • You can accomplish this by using Node.appendChild() with setting the required attributes;

    String script = "var p = document.createElement('input');var ele = document.getElementById('post-ad_title');p.setAttribute('type','text');p.setAttribute('name','imageToAdd');p.setAttribute('value','3566'); ele.appendChild(p);";
    ((JavascriptExecutor) driver).executeScript(script);