js用xpath定位获取元素

一、获取单个元素

1、html

<html>
    <head>
        <meta charset="utf-8">
		<script src="test.js">script>
    head>
    <body>
        <select style="width: 100%;">
            <option value="0">option>
            <option value="1">张三option>
            <option value="2">李四option>
            <option value="3">王五option>
            <option value="4">刘六option>
        select>
        <button type="button"  id="a" style="width: 100px; height: 50px;background-color: #eee;">点击button>
		 
    body>
 
html>

2、js

//DOM加载时加载testXpath
addLoadEvent(testXpath)
//测试Xpath
function testXpath(){
	document.evaluate("/html/body/button",document).iterateNext().onclick = function(){
		var element = document.evaluate("/html/body/select",document).iterateNext();//获取到select元素
		var index = element.selectedIndex;//获取元素下标
		console.log(element.options[index].text)

	}
}
//文档加载函数
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
      }
    }
}


3、js的优化

将xpath封装,使用更加方便

//DOM加载时加载testXpath
addLoadEvent(testXpath)
//测试Xpath
function testXpath(){
		getElementByXpath("/html/body/button").onclick = function(){
		var element = getElementByXpath("/html/body/select");//获取到select元素
		var index = element.selectedIndex;//获取元素下标
		console.log(element.options[index].text);
	}
}
//文档加载函数
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
      }
    }
}
//封装xpath
function getElementByXpath(xpath){
	var element = document.evaluate(xpath,document).iterateNext();
	return element;
}


二、如何获取xpath

  • 1、打开元素所在的网页
  • 2、打开开发者模式(F12)
  • 3、点击这个小箭头选中你要定位的元素
    js用xpath定位获取元素_第1张图片
  • 4、在这里右键——》copy——》copy xpathjs用xpath定位获取元素_第2张图片

你可能感兴趣的:(JavaScript,javascript)