Home > Software design >  Select multiple values with jquery
Select multiple values with jquery

Time:10-18

my issue is finding all objects with a specific prefix in the classname, like in the following portion of html I'd like to be able to get us_mr and us_she with a single statement.

<div>
 <div class="us_me">Some about me</div>
 <div class="us_she">Some about she</div>
 <div class="they_she">Some about others</div>
</div>

this what I tried

$(".^us_")

assuming it would have found

<div class="us_me">Some about me</div>
<div class="us_she">Some about she</div>

but got syntax error

CodePudding user response:

You might want to try with $("div[class^='us_']")

Working demo

console.log($("div[class^='us_']").length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div class="us_me">Some about me</div>
  <div class="us_she">Some about she</div>
  <div class="they_she">Some about others</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Correct syntax for wildcard is: [attribute^="value"].

Example:

$("[class^='us_']").addClass('someClass');
.someClass {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div class="us_me">Some about me</div>
  <div class="us_she">Some about she</div>
  <div class="they_she">Some about others</div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related