简体   繁体   中英

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?

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>

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>

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".

在此处输入图像描述

  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.

在此处输入图像描述

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

在此处输入图像描述

Documentation:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM