WPF WebBrowser – getElementsByClassName Isn’t Working

02/10/2013

Working on a WPF app for a customer we’ve faced a strange problem, our WPF app display some HTML content and allow user actions on the Web Browser control – Expend and Collapsed div elements.

Because the JavaScript code is simple I don’t want to add any external library to our generated HTML and JavaScript code.

Here is how the Expend and Collapse code looks like:

function toggleAllItems(show) {
    var text = '+'; var style = 'none';
    if (show) {
        text = '-'; style = 'block';
    }
    var allexpenders = document.getElementsByClassName('expender-container');
    for (var i = 0; i < allexpenders.length; i++) {
        allexpenders[i].style.display = style;
    } 
    var toggles = document.getElementsByClassName('toggle');
    for (var i = 0; i < toggles.length; i++) {
        toggles[i].innerText = text;
    }
}
function expendAll() {
    toggleAllItems(true);
}
function collapseAll() {
    toggleAllItems(false);
}

Once I run the app I saw the HTML documents just fine except I received the following error once I clicked on the Expend\Collapsed Items.  (The object is the document, get element by id works)

image

If I open the same HTML + JavaScript code in IE (10) it works just fine, so I had to implement the getElementByClassName

<script>
function getElementsByClassName(node, classname) {
    if (node.getElementsByClassName) {
        return node.getElementsByClassName(classname);
    }
    else {
        return (function getElementsByClass(searchClass, node) {
            if (node == null)
                node = document;
            var classElements = [];
            var tags = node.getElementsByTagName("*"), pattern = new RegExp("(^|\\s)\"+searchClass+\"(\\s|$)"), i, j;
            for (i = 0, j = 0; i < tags.length; i++) {
                if (pattern.test(tags[i].className)) {
                    classElements[j] = tags[i];
                    j++;
                }
            } return classElements;
        })(classname, node);
    }
}
</script>
Usage:
function toggleAllItems(show) {
    var text = '+'; var style = 'none';
    if (show) {
        text = '-'; style = 'block';
    }
    var allexpenders = getElementsByClassName(document, 'expender-container');
    for (var i = 0; i < allexpenders.length; i++) {
        allexpenders[i].style.display = style;
    } 
    var toggles = getElementsByClassName(document, 'toggle');
    for (var i = 0; i < toggles.length; i++) {
        toggles[i].innerText = text;
    }
}
function expendAll() {
    toggleAllItems(true);
}
function collapseAll() {
    toggleAllItems(false);
}
Add comment
facebook linkedin twitter email

Leave a Reply