Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all elements whose name starts with a specific string in CSS

I would like to select all the html elements that start with "my-element".

For example:

my-element-1 {

    background-color: red;
    ...
}
my-element-2 {
    background-color: red;
    ...
}
my-element-3 {
    background-color: red;
    ...
}

would be something like:

[tag*="my-element"] {
    background-color: red;
    ...
}

That syntax works when selecting classes like this:

div[class^='myclass'], div[class*=' myclass']{
    color: #F00;
}

How can I do this?

like image 335
João Pedro Sá Medeiros Avatar asked Jul 19 '18 13:07

João Pedro Sá Medeiros


People also ask

How do I select specific items in CSS?

The CSS id Selector The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.

What is the * selector CSS?

The * selector in CSS is used to select all the elements in a HTML document. It also selects all elements which are inside under another element. It is also called universal selector.

What CSS selector matches all list items?

The CSS selector list ( , ) selects all the matching nodes.


2 Answers

Nope, there is no CSS selector like "wildcard elements" to retrieve elements based on a partial element name.

You can:

A) Use class-names or any other attributes, since element attributes can be accessed using selectors with regular expressions. (As in your question.)

my-element[my-attribute] { … }

B) Use a CSS pre-processor like SCSS to generate a list of such element names:

@for $i from 1 through 3 {
  my-element-#{$i} {
    background-color: red;
  }
}

C) Or just write them one after another in the CSS, delimited by a comma: (This is the same as writing each rule independently as in your question.)

my-element-1,
my-element-2,
my-element-3 {
    background-color: red;
}
like image 113
feeela Avatar answered Oct 19 '22 18:10

feeela


If you want to create your own html tags it is not HTML5 format. Dont really know how this "elements" part suppose to work in your code, but you can use:

div[id^="my-element"]{//code}

It is a selector that picks elements by the same beginning part. Cite from: W3C

E[foo^="bar"] an E element whose "foo" attribute value begins exactly with the string "bar"

For example:

<html>
<head>
<style>
div[id^="my-element"]{
//code}</style>
</head>
<body>
<div id="my-element-1">Content</div>
<div id="my-element-2">Content</div>
</body>
</html>

Hope it helps.

like image 22
PStarczewski Avatar answered Oct 19 '22 20:10

PStarczewski