0

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?

5
  • 1
    this maybe helps Commented Jan 2, 2023 at 12:47
  • @ericmp Easier than tagName, id and classList? Commented Jan 2, 2023 at 12:53
  • im kinda confused on what u want to achieve. if u want to select an element by id u can use document.querySelector('#some-id'). not sure what is ur question Commented Jan 2, 2023 at 12:56
  • 1
    @ericmp thanks, that seems to be like what I was thinking about. If you write that as an answer, I will mark it as answered (if no better solutions show up). Commented Jan 2, 2023 at 13:00
  • @Andy I am not trying to select the element. I want to convert an element to a string presentation in the QuerySelector syntax. Commented Jan 2, 2023 at 13:02

3 Answers 3

1

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>

Sign up to request clarification or add additional context in comments.

6 Comments

Wow, that is some condensed code. 🤩
There's a bug when there are no classes: <div> -> "div0". Also, if there is an ID, then technically you could omit classes also. But note that in the real world there are documents with duplicate IDs.
I fixed a small bug where the leading dot for the classes was missing.
All works again.
As HTML can't have "fatal" errors, the rule about unique IDs is more like a guideline. So browsers have to handle duplicate IDs, so in reality IDs are just a special kind of class.
|
1

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>

1 Comment

This breaks in case there are no classes, and will always output "#" even if there is no id. (I see my question was not clear about that, have edited the question.)
1

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:

1 Comment

You a correct, basically what I want is a function that returns the string you see in DevTools. ("div#some-id.class-1.class-2")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.