Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround for :empty Selector Not Being Updated When Children Added in IE11

I have simple css statement I want to apply to some HTML that basically only shows an element when its previous sibling is not empty. The use case is to only show a "Clear" button when a list has items in it.

<ul></ul>
<button>Clear</button>

ul:empty + button
{
    display: none;
}

The problem is that whenever my javascript inserts a new list item into the list, Chrome appears to work correctly and automatically make the button visible. IE11 however fails to show the Clear button. This JS fiddle illustrates the problem: http://jsfiddle.net/xw4nbnz3/

What is the easiest workaround for this problem to make ie11 work? Preferably staying in CSS only.

like image 314
Mark Murfin Avatar asked Jan 14 '15 16:01

Mark Murfin


1 Answers

Pretty sure I'd seen this before, but I can't find the previous question anymore so I'll take a stab at it.

This looks like a typical repaint bug: IE will understand your CSS just fine... if the list starts out with items, and if you write a function to empty the list instead, it will not update the button either. Unfortunately, repaint bugs aren't known for having pure CSS workarounds.

Fortunately, they don't usually need them. Since this only happens when you change the DOM, you can easily work around this within the JS, and it doesn't take very many lines. It looks like removing the list itself first, before inserting the new item, then putting the list back in resolves this issue whilst not creating any problems in other browsers:

function AddListItem()
{
    var mylist = document.getElementById("mylist");
    if (!mylist)
        return;

    var parent = mylist.parentElement;
    var button = mylist.nextElementSibling;
    parent.removeChild(mylist);

    var li = document.createElement("li");
    li.appendChild(document.createTextNode("Hello, world!"));
    mylist.appendChild(li);

    parent.insertBefore(mylist, button);
}

Tested on IE11 on Windows 7, Windows 8.1, and Windows 10 RTM (build 10240), and Microsoft Edge on Windows 10 RTM. Note that removing the list after inserting the item (right before putting it back in) does not work; you will need to remove it first.

like image 148
BoltClock Avatar answered Nov 03 '22 00:11

BoltClock