Skip to content ↓

:first-child pseudoclass and sibling combinator in IE7

As of version 7, Internet Explorer (IE) supports :first-child selector and sibling combinator (+) that allow to make HTML code much cleaner.

There is a limitation though: if HTML code has a comment in place where browser expects to see an element according to selector, IE7 will be “confused” and will not apply styles to the actual element located next to the comment.

In the following example, styles will be applied to paragraphs in all popular browsers (including IE8+), but not in IE7:

    <!-- Comment before first element -->
    <p>First paragraph.</p>
    <!-- Comment between elements -->
    <p>Second paragraph.</p>
P:first-child {color: #0f0; } /* first child paragraph */
P + P {color: #00f; } /* paragraph after another paragraph */

Fortunately, there is a workaround for this issue: HTML comments as DOM nodes can be dynamically removed from DOM tree with JavaScript once HTML page is loaded. This can be done, for example, with the following function:

function removeComments() {
    var elems = document.getElementsByTagName('*'),
        count = elems.length,
        comments = [];

    for (var i = 0; i < count; i++) {
        var elem = elems[i],
            childNodes = elem.childNodes,
            childCount = childNodes.length;

        for (var j = 0; j < childCount; j++) {
            var node = childNodes[j];

            if (8 === node.nodeType) {

    var commentsCount = comments.length;

    for (var k = 0; k < commentsCount; k++) {

    // Forcing reflow (rerendering) to ensure styles are applied
    document.body.className = document.body.className;

Live demo