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?

Peter
  • 2,874
  • 2
  • 31
  • 42
  • 1
    [this](https://stackoverflow.com/a/48081741) maybe helps – ericmp Jan 02 '23 at 12:47
  • @ericmp Easier than tagName, id and classList? – mplungjan Jan 02 '23 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 – ericmp Jan 02 '23 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). – Peter Jan 02 '23 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. – Peter Jan 02 '23 at 13:02

3 Answers3

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
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>
mmh4all
  • 1,612
  • 4
  • 6
  • 21
  • 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.) – Peter Jan 02 '23 at 13:09
0

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:

ericmp
  • 1,163
  • 4
  • 18
  • 1
    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") – Peter Jan 02 '23 at 14:34