Sai Avinash Duddupudi
Sai Avinash Duddupudi

Reputation: 45

Get CSS Selector/Path of HTML elements

I filtered the HTML class elements using

elements = document.querySelectorAll("div._3arMG")

Now that I have a list of HTML elements I need, I want the CSS Selector/Path for each HTML element in the elements list.

CSS Selector when I right click on HTML ELement in Console -> Copy -> Copy Selector -> #root > div._3arMG

Please suggest how do I get this CSS Selector using Javascript?

Upvotes: 1

Views: 1993

Answers (2)

Sascha A.
Sascha A.

Reputation: 4616

You can do it recursivly with parentElement for the next node above. Getting for every node the tagname by nodeName, the classes with classList and the id.

Edited: Because Id's are unique I stop if an id occurs in the path.

let elements = document.querySelectorAll("div._3arMG");

let result = [];
elements.forEach(el => {
    result.push(getPath(el));
})
console.log(result);

function getPath(el) {
    let act = el.nodeName;
    el.classList.forEach(cl => act += '.' + cl);
    if (el.id) act += '#' + el.id;
        
    if (!el.id && el.parentElement) {
        let res = getPath(el.parentElement);
        res.push(act);
        return res;
    } else {
        return [act];
    }
}
<div class='Wrapper'>
  <div class="_3arMG myClass">
    Test
  </div>
  <table id='myTable'>
    <tr>
      <td>
        <div class="_3arMG">My span</div>
      </td>
    </tr>
  </table>
</div>

Upvotes: 0

hgb123
hgb123

Reputation: 14891

You could use either Element.querySelector() or Element.querySelectorAll(), choose which suits your case

const elements = document.querySelectorAll("div._3arMG")

for (const element of elements){
  const subElements = element.querySelectorAll('.someclass')
  // or
  const subElement = element.querySelector('.someclass')
  
  // ... 
}

Reference

Element.querySelector()

Element.querySelectorAll()

Upvotes: 2

Related Questions