Home > Net >  JS: Create a CSS selector string from an HTML element
JS: Create a CSS selector string from an HTML element

Time:01-03

In JavaScript, given I have selected an HTML element, for example:

<div id="some-id" >...</div>

Is there an easy way to create the corresponding CSS selector/QuerySelector?

"div#some-id.class-1.class-2"

Or is the only way to construct this string manually using tagName, id and classList?

CodePudding user response:

tagName, id and classList are quite simple to use if you want a list of selectors

If you have an ID, you do not need the rest:

const divSelectors = tag => [...document.querySelectorAll(tag)]
  .map(tag => tag.id ? `#${tag.id}` : `${tag.tagName.toLowerCase()}${tag.classList.length ? `.${[...tag.classList].join('.')}` : ''}`)
console.log(divSelectors("div"))
<div>...</div>
<div id="id1" >...</div>
<div id="id2" >...</div>
<div id="id3" >...</div>
<div >...</div>
<div id="id4">...</div>

But if you insist:

const divSelectors = tag => [...document.querySelectorAll(tag)]
  .map(tag => `${tag.tagName.toLowerCase()}${tag.id?`#${tag.id}`:''}${tag.classList.length ? `.${[...tag.classList].join('.')}` : ''}`)
console.log(divSelectors("div"))
<div>...</div>
<div id="id1" >...</div>
<div id="id2" >...</div>
<div id="id3" >...</div>
<div >...</div>
<div id="id4">...</div>

Surprisingly enough we can use querySelector on multiple divs with the same ID

console.log(document.querySelector("#aDiv").textContent)
console.log(document.querySelector("#aDiv.three.four").textContent)

console.log([...document.querySelectorAll("#aDiv")].map(div => div.textContent))
<div id="aDiv" >First</div>
<div id="aDiv" >Second</div>

CodePudding user response:

This is a possible solution for you problem

function createCssSelector(el){
    return `${el.nodeName}${el.id ? '#' el.id : ''}${el.getAttribute('class') ? '.' el.getAttribute('class').split(' ').join('.') : ''}`;
}

console.log(createCssSelector(document.querySelector('#some-id')));

console.log(createCssSelector(document.querySelector('#some-id-2')));

console.log(createCssSelector(document.querySelector('span')));

console.log(createCssSelector(document.querySelector('#some-id-3')));
<div id="some-id" >...</div>

<p id="some-id-2" >...</p>

<span >...</span>

<p id="some-id-3" >...</p>

CodePudding user response:

Having this HTML:

<div id="some-id" >...</div>

You can select the div using different techniques/ways:

document.querySelector("#some-id")

document.querySelector(".class-1.class-2")

document.getElementById("some-id")

document.querySelector("#some-id.class-1.class-2")

...

Depending on what are you doing you want to use one or other one. If there is no context, I'd stick to the first one.

* (Extra tip) If you are in a web browser, you can:

  1. Open up the DevTools.
  2. Click on the cursor icon - "Select an element in the page to inspect it".

enter image description here

  1. Click an element in the page.
  2. Go to the devtools console.
  3. Write $0. If you don't return, it will show you the full selector.

enter image description here

  1. If you return, it will log you the selected element.

enter image description here

Documentation:

  • Related