Different results selecting HTML elements with XPath in Firefox and Internet Explorer

后端 未结 10 793
-上瘾入骨i
-上瘾入骨i 2021-01-18 10:34

I\'m trying to select a specific HTML element in a document, for firefox i just use:

xpathobj = document.evaluate(xpath, document, null,
               XPath         


        
10条回答
  •  [愿得一人]
    2021-01-18 11:38

    Hi well in the end i came up with my own dodgy solution, any sugestions on improving it would be greatly apreciated. It makes use of some prototype functionality:

    Works in IE5+ with xpath of the form "/HTML/BODY/DIV[9]/DIV[2]"

    function getXPathElement (xpath , element) {

    //Specific to project, here i know that the body element will always have the id "top"
    //but otherwise the element that is passed in should be first element in the xpath 
    //statement eg. /HTML/BODY/DIV the element passed in should be HTML
    if(!element){
        element = $("top");
        var xpathArrayIndex = 3;
    } else {
        var xpathArrayIndex = 1;
    }
    //split the xpath statement up
    var xpathArray = xpath.split("/");
    
    var carryOn = true; 
    while(carryOn){
        decendents = element.childElements();
        //check to see if we are at the end of the xpath statement
        if(xpathArrayIndex == xpathArray.length){
            return element;
        }
        //if there is only one decendent make it the next element
        if(decendents.size() == 1) {
            element = decendents.first();
        } else {
        //otherwise search the decendents for the next element
            element = getXPathElementByIndex(decendents, xpathArray[xpathArrayIndex]);
        }
        xpathArrayIndex++;
    }
    

    }

    function getXPathElementByIndex(decendents, xpathSegment){

    var decendentsArray = decendents.toArray();
    //seperate the index from the element name
    var temp = xpathSegment.split("[");
    var elementName = temp[0];
    //get the index as a number eg. "9]" to 9
    var elementIndex = +temp[1].replace("]", "");
    //the number of matching elements
    var count = 0;
    
    //keeps track of the number of iterations
    var i = 0;
    while(count != elementIndex) {
        //if the decendent's name matches the xpath element name increment the count
        if(decendentsArray[i].nodeName == elementName){
            count++;
        }
        i++;
    }
    var element = decendentsArray[i - 1];
    return element;
    

    }

    Thanks to everyone for thier help, either way i learnt a fair bit about various javascript frameworks.

提交回复
热议问题