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

1

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

    
asked by anonymous 21.02.2018 / 11:54

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 complete look at: link

[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 are the ones I use the most

Tip

There is a conflict. If you are going to use JQuery and CSS to style your page, you would face problems because JQuery "normally" comes last, hence you would have to decide if you would just use CSS to style or just JQuery. But you can do something like this to avoid this:

Using :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>

link

    
21.02.2018 / 12:02
0

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

    
21.02.2018 / 13:27