-2

I am new to jquery and programming.
Instead of using the #id for the addClass in jquery, can we send the variable as the id.
Below is the proper code using #id.
what i been thinking is using variable such as x

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
.red{
background-color:red;
}
</style>
<script>
var x=1;
$('#1').addClass('red');
</script>

</head>

<body>
<section id=1>1</section>

<section id="2" class="sec">2</section>
<section id="3" class="sec">3</section>
<section id="4"  class="sec">4</section>
<section id="5"  class="sec">5</section>
</body>

</html>  

is there any way to send variable directly as the id.something like this

var x=1;
   $(x).addClass('red');
Jonathan
  • 2,700
  • 4
  • 23
  • 41
vineeth
  • 53
  • 2
  • 8
  • Note that `#1` is an invalid selector. It works with jQuery (though not officially, and only if it's on its own). It does not work with CSS or `querySelector`/`querySelectorAll`. CSS ID selectors cannot start with an unescaped digit. – T.J. Crowder Jun 22 '17 at 11:14

3 Answers3

3

Try this

 $('#'+x).addClass('red');
VenkyDhana
  • 905
  • 5
  • 16
2

you can use

   var x=1;
   $("#"+x).addClass('red');
Srinivas ML
  • 732
  • 3
  • 12
0

You need to concatenate id selector(#) while creating jquery object of element:

$('#'+x).addClass('red');
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125