Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can this function be achieved #337

Closed
rookiefront opened this issue Jul 17, 2020 · 3 comments
Closed

Can this function be achieved #337

rookiefront opened this issue Jul 17, 2020 · 3 comments

Comments

@rookiefront
Copy link

Can this function be achieved,If you have enough time
jquery - How to calculate the XPath position of an element using Javascript?

Javascript get XPath of a node

@rookiefront
Copy link
Author

function getXPathForElement(element) {
    const idx = (sib, name) => sib
        ? idx(sib.previousElementSibling, name||sib.localName) + (sib.localName == name)
        : 1;
    const segs = elm => !elm || elm.nodeType !== 1
        ? ['']
        : elm.id && document.getElementById(elm.id) === elm
            ? [`id("${elm.id}")`]
            : [...segs(elm.parentNode), `${elm.localName.toLowerCase()}[${idx(elm)}]`];
    return segs(element).join('/');
}

image

@rookiefront
Copy link
Author

my problem is solved

func  GetCssSelector(elm *goquery.Selection) string {

	path := []string{}
	for {
		selector := strings.ToLower(goquery.NodeName(elm))
		if selector =="" {
			break
		}
		//如果是ID选择器直接退出
		id_val, id_exists := elm.Attr("id")
		if id_exists && id_val != "" {
			selector+="#"+id_val
			path = append(path,selector)
			break
		}else{
			sib := elm
			nth := 1
			sib.PrevAll().Each(func(i int, selection *goquery.Selection) {
				//fmt.Println("234",strings.ToLower(goquery.NodeName(selection)) , selector)
				if strings.ToLower(goquery.NodeName(selection)) == selector {
					nth++
				}

			})
			if nth != 1 {
				selector += fmt.Sprintf(`:nth-of-type(%d)`,nth)
			}
		}
		path = append(path,selector)
		elm = elm.Parent()
	}
	path = Reverse(path)
	join := strings.Join(path, " > ")

	return join
}

@mna
Copy link
Member

mna commented Jul 17, 2020

For future reference, see #198 . Closing since you seem to be happy with the solution you have.

@mna mna closed this as completed Jul 17, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants