使用jquery

时间:2016-07-12 08:16:45

标签: javascript jquery html xpath

如何在jquery中的/html/body/div[1]/section/div[2]/div[2]/div/div/div[2]/div/form/div[1]/div[4]/div/div之类的xpath之后附加数据。

我可以使用php附加,但我想在jquery中。

1 个答案:

答案 0 :(得分:0)

使用jQuery

简单干净......让我们做一个很好的功能:

将xPath转换为jQuery Sellector,使用jQuery获取元素,然后返回它。

// Get an element by xpath
// Using jQuery
function getJQueryElementByXpath(xpath){
    var selector;

    // Remove any '/' on the beginning of the string
    // ex "/html/div" -> "html/div"
    selector = xpath.replace(/^\s*\/\s*/g, "");

    // Convert '/' to ' > ' to express child search
    selector = selector.replace(/\s*\/\s*/g, " > ");

    // Convert '[number]' to ':eq(number)'
    selector = selector.replace(/\[(\d+)\]/g, ":eq($1)");

    // Return the jQuery element
    return jQuery(selector);
}

现在你可以获得你的元素并附加你想要的东西。

// My xpath
var xpath = "/html/body/div[1]/section/div[2]/div[2]/div/div/div[2]/div/form/div[1]/div[4]/div/div";

// Get the element with jQuery
var myXpathElement = getJQueryElementByXpath(xpath);

// Lets append an other element
myXpathElement.append(exampleElement);

没有jQuery

如果你不想使用jQuery,只在现代浏览器上使用javascript

(Chrome 4.0,Internet Explorer 9.0,Firefox 3.5,Safari 3.2,Opera 10.0或更高版本,参考http://caniuse.com/#feat=queryselector

// Get an element by xpath
// Using Javascript (on modern browsers)
// Need support for document.querySelector using css3
function getElementByXpath(xpath){
    var selector;

    // Remove any '/' on the beginning of the string
    // ex "/html/div" -> "html/div"
    selector = xpath.replace(/^\s*\/\s*/g, "");

    // Convert '/' to ' > ' to express child search
    selector = selector.replace(/\s*\/\s*/g, " > ");

    // Convert '[number]' to ':nth-of-type(number+1)'
    selector = selector.replace(/\[(\d+)\]/g, function(n){ return ":nth-of-type(" + (++n[1]) + ")" });

    // Return the javascript element
    return document.querySelector(selector);
}