Peter
Peter

Reputation: 3008

JS: Create a CSS selector string from an HTML element

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

<div id="some-id" class="class-1 class-2">...</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?

Upvotes: 0

Views: 1071

Answers (3)

ericmp
ericmp

Reputation: 2257

Having this HTML:

<div id="some-id" class="class-1 class-2">...</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:

Upvotes: 1

mplungjan
mplungjan

Reputation: 177965

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" class="class-1 class-2">...</div>
<div id="id2" class="class-3 class-4">...</div>
<div id="id3" class="class-5 class-6">...</div>
<div class="class-7 class-8">...</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" class="class-1 class-2">...</div>
<div id="id2" class="class-3 class-4">...</div>
<div id="id3" class="class-5 class-6">...</div>
<div class="class-7 class-8">...</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" class="one two">First</div>
<div id="aDiv" class="three four">Second</div>

Upvotes: 1

mmh4all
mmh4all

Reputation: 1753

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" class="class-1 class-2 class-4">...</div>

<p id="some-id-2" class="black blue white">...</p>

<span class="black blue white">...</span>

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

Upvotes: 1

Related Questions