Generate CSS Selector for target element
2022年5月1日小于 1 分钟
Generate CSS Selector for target element
Question
Given a DOM tree and a target element, generate a valid selector to target it.
For example, for a DOM tree like below
<div>
<p>BFE.dev</p>
<div>
is
<p>
<span>great. <button>click me!</button></span>
</p>
</div>
</div>
There could be more than 1 answer.
let selector = generateSelector(root, target) // 'button'
expect(root.querySelector(selector)).toBe(target)
selector = generateSelector(root, target) // 'div > div > p > button'
expect(root.querySelector(selector)).toBe(target)
Code
/**
* @param {HTMLElement} root
* @param {HTMLElement} target
* @return {string}
*/
function generateSelector(root, target) {
// your code here
}