0

i have a var value i want to pass that as id to my jquery how to that

here is my sample code

$( "span" ).click(function() {
var id=1;
  $("#1>li").remove();//now it exactly removes the id 1 but how to pass var id insted of 1
});
<html >
<head>
  <meta charset="utf-8">
  <title>remove demo</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
 <span>hey</span>
<ul id="1">Hello
how are
<li>you?</li>
</ul>
<ul id="2">Hello
how are
<li>you?</li>
</ul>

</body>
</html>

now it exactly removes the id=1 but how to pass var id instead of 1

Suhas
  • 83
  • 2
  • 17
  • 1
    `$("#"+id+">li")` concat – guradio Mar 14 '17 at 07:18
  • Note that although you're trying to use jQuery here, the problem really boils down to "How do I create the string `"#1>li"` if the `1` is in a variable `id=1`?" The fact that you plan to then use that string in a call to the `$()` function is irrelevant. (If you are trying to remove the item that was clicked, that is a different problem, but your sample has a click handler on the only span in your HTML, so...) – nnnnnn Mar 14 '17 at 07:25
  • @nnnnnn its just a sample code i wasn't knowing how it works so i asked with that sample code thanks for your suggestion – Suhas Mar 14 '17 at 07:32

1 Answers1

1

Use simple string concatenation to generate the selector string.

$('#' + id  + '>li').remove();
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188