Search code examples
htmlxmldom

Is there an error in my code or does it have to do with my Firefox 12 browser?


I copied the following code from a tutorial, but still couldn't figure out whether I made a mistake somewhere or whether it has to do with the browser support.

<html>
<head>
<script type="text/javascript">

function loadXMLDoc(dname)
{   
    if(window.XMLHttpRequest)
    {
        xhttp = new XMLHttpRequest();
    }
    else
    {
        xttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    xhttp.open("GET", dname, false);
    xhttp.send();
    return xhttp.responseXML;
}

function change(text)
{
    var xmlDoc = loadXMLDoc("dom.xml");
    var x = xmlDoc.getElementsByTagName("title")[0].childNodes[0];
    
    x.nodeValue = text;
    
    var y = xmlDoc.getElementsByTagName("title");
    for(i=0; i<y.length; i++) 
    {
        document.write(y[i].childNodes[0].nodeValue+"<br />");
    }
}

function remove(node)
{
    xmlDoc = loadXMLDoc("dom.xml");
    var y = xmlDoc.getElementsByTagName(node)[0];
    
    xmlDoc.documentElement.removeChild(y);
    alert("The element "+node+" has been removed!");
}

function prove(u)
{
    var x = xmlDoc.getElementsByTagName(u);
    for (i=0; i<x.length; i++)
    {
        document.write(x[i].childNodes[0].nodeValue);
        document.write("<br />");
}
    
</script>
</head>
<body>
    <input type="button" value="remove" onclick="remove('book')" />
    <input type="button" value="prove it" onclick="prove('book')" />
</body>

</html>

Update

Here's an XML file that may help:

<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>
    <book category="cooking">
        <title lang="en">Everyday Italian</title>
        <author>Giada</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
    <book category="cooking">
        <title lang="en">Book 2</title>
        <author>Giada</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
    <book category="cooking">
        <title lang="en">Book 3</title>
        <author>Giada</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
</bookstore>

Solution

  • I think the problem might be because of document.write

    Any document.write statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page.

    Also there is a } missing after the for statement of prove function

    Try using innerHTML on a div or some html element to overcome this issue.

    Other than that I don't find any issues with your code