5

Is there a way to select an element by name in CSS using a wildcard?

For example, with these elements:

<my-element-one></my-element-one>
<my-element-two></my-element-two>
<div></div>

Could I only select every one starting with 'my-element'? For example like this:

my-element-* {color: red;}
HotStuff68
  • 925
  • 1
  • 10
  • 13
  • You can do that using a javascript script. once you select them with the script, you can give them a common class (for instance) and work with that class, or even work directly on their style attribute. This may be a starting point for you: http://stackoverflow.com/questions/4275071/javascript-getelementbyid-wildcard – Marcelo Myara May 25 '15 at 21:15

3 Answers3

8

No. Only attribute selectors have any kind of wildcard syntax in CSS.

It sounds like your XML application design might be better off using fewer types and using attributes to distinguish between subsets of them.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
7

As Quentin already said, such selectors are not available. An easy solution to this is to put the element's name also as a class name:

<my-element-one class="my-element-one"></my-element-one>
<my-element-two class="my-element-two"></my-element-two>
<div></div>

This way you could use attribute wildcard syntax, for example

 [class^="my-element-"]

would target all elements that have a class attribute beginning with my-element-.

You can also use $= (ends with), *= (contains) and more, check

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

To make it more fail-safe and dedicated to the task, the best idea is probably to have a data-tagname attribute:

<my-element-one data-tagname="my-element-one"></my-element-one>
<my-element-two data-tagname="my-element-two"></my-element-two>

This would make the starts with attribute selector variant more failsafe, since, other than class, there won't be anything additional or dynamic inside it.

[data-tagname^="my-element-"]
connexo
  • 53,704
  • 14
  • 91
  • 128
-3

You can always add a common class and set of one or more additional classes to element.

You can put your style that is common to all elements in the common class' css and then override it as needed with the additional css class.

for example:

<div class="my-element my-element-one"></div>
<div class="my-element my-element-two"></div>
<div></div>

css:

div.my-element
{
     height: 100px;
     width : 100px;
}

div.my-element-one
{
     color: red;
}

div.my-element-two
{
     color: blue;
}
dhruvpatel
  • 1,249
  • 2
  • 15
  • 23