How to add css to all elements whose id contains "..."?

Asked

Viewed 413 times

1

I have several elements whose id contain, for example, "elem", may be "%elem" or "elem%", may have characters before the String elem as after or before and after ("%elem%"). And I would like to add to all the elements that css with jQuery. How can I select all elements that contain "elem" in id?

  • Wouldn’t it be better to assign the same class to the various elements you want to take? Rather than relying on part of each one’s name?

  • @Isac this is good for when Voce wants to do css like for example: input-bordered-white (using -).

2 answers

4


Just use this selector:

[id*="elem"] {
    height: 100px;
    width: 100px;
    background: black;
}
<div id="opa-elem-ops"></div>

You can take a full look at: https://www.w3schools.com/cssref/css_selectors.asp

[attribute*="target"]  #TODO ATRIBUTO QUE TEM "TARGET", INDEPENDENTE DO LUGAR, SERÁ PEGO.
e
[attribute^="target"]  #TODO ATRIBUTO QUE COMEÇA COM "TARGET" SERÁ PEGO

They’re the ones I use the most

Tip

There is a conflict. If you’re going to use Jquery and CSS to style your page, you’d face problems, because Jquery "usually" comes last, so you’d have to decide whether to use only CSS to style or just Jquery. But you can do something like that to prevent it:

Using the :not()

setTimeout(function(){
    $('[id*="elem"]:not([id*="elem1"])').css({
    background: 'dodgerblue',
    height: '100px',
    width: '100px'
  });
}, 1000);
[id*="elem1"] {
  background: black;
  width: 100px;
  height: 100px;
}
<!-- esse cara vai receber black do CSS, mas se não usar :not() em JQuery, o JQuery vai colocar dodgerblue em tudo que tem elem, porém não quero estilizar o elem1 -->
<div id="ops-elem-opa"></div>
<!--esse cara nao deveria receber dodgerblue do JQuery -->
<div id="ops-elem1-opa"></div>


<!--ignore-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

https://jsfiddle.net/thecodermarcelo/wbL50by6/9/

0

A simple way to do this, not necessarily needing to link to the element ID, would be to assign a class, and use Jquery to make the change. For example $(".classe").css(...). And this class can also be used to assign properties, as well as events (click, change, etc...)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.