0

Just wandering, will it be possible to add class into html element with partially id information with jquery.

Example:

I have the following html code

<e id="1-1">1.1</e>
<e id="1-2">1.2</e>
<e id="2-1">2.1</e>
<e id="2-2">2.2</e>

Currently I'm using the following code to add in the class:

 $("e[id=1-1]").addClass("keyWord");

Would it be possible to pass in the partially id like 1 and it will add the class for element with id 1-1 and 1-2?

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Jin Yong
  • 42,698
  • 72
  • 141
  • 187
  • PS: what kind of HTML tag is ``? You mean ``? – Roko C. Buljan Sep 19 '19 at 22:13
  • Related: https://stackoverflow.com/questions/33615334/jquery-finding-partial-class-name/33615377#33615377 – Taplar Sep 19 '19 at 22:19
  • Side note, if you are doing exact id matching, you should avoid `[id=""]` selectors, as that is an attribute selector, rather than an id selector. Attribute selectors do not benefit from performance logic related to ids. An attribute can be on any element, so the browser has to check every single element in the context. Where as an id can only be on one element, and the browser hashes them in some manner for quick lookup, so they are super fast. – Taplar Sep 19 '19 at 22:21

2 Answers2

0

To target an attribute value which starts with - use the Starts With selector ^=

 $('[id^="1-"]').addClass("keyWord");
.keyWord {background: red;}
<span id="1-1">1.1</span>
<span id="1-2">1.2</span>
<span id="2-1">2.1</span>
<span id="2-2">2.2</span>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You can do it with pure CSS too:

[id^="1-"]{
  background: red;
}
<span id="1-1">1.1</span>
<span id="1-2">1.2</span>
<span id="2-1">2.1</span>
<span id="2-2">2.2</span>

You have at your disposition other ones too: Contains *= and Ends With $= and more. Find out here MDN - Attribute selectors

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

you could write a simple js that retrieves the element and adds to its class list.

let element=document.getElementById("1-1");
    element.classList.add("1-1-1");
Ndubuisi Jr
  • 461
  • 6
  • 13