Python selenium add li to ul

Viewed 347

I have this html code

<ul class="select-items">
     <li class="select-items-item" data-label="<first>">Number 1</li>
</ul>

and I want to add a new li like <li class="select-items-item" data-label="<second>">Number 2</li>

What i tried so far : I click the list using the xpath ( that works fine because I can see the list open), addAttribute to the element (that is the tricky part, not working), add javascript code ( not working either)

liItem = """
     var ul = document.getElementByXpath('//*[@class="select-items"]');
     var li = document.createElement("li");
     li.appendChild(document.createTextNode("Element 4"));
     ul.appendChild(li);
 """
 driver.execute_script(liItem);

Any suggestions?

1 Answers

To add the following <li> i.e.

<li class="select-items-item" data-label="<second>">Number 2</li>

You can use the following line of code:

scriptTxt = """
    var ul = document.getElementsByClassName('select-items').item(0);
    var li = document.createElement('li');
    li.setAttribute('textContent', 'Number 2');
    ul.appendChild(li);body.appendChild(li);
"""
driver.execute_script(scriptTxt)

References

You can find a couple of relevant detailed discussions in:

Related