Miloni Shah
Miloni Shah

Reputation: 25

How do I access an element if the id which I want to access is stored in a variable

I am trying to dynamically create elements and hence dynamically giving them the value. So if I want to access an element using a value which is stored in a variable, how do I do that ?

I've tried using $("#'"+g+"'") but it didn't work

var text1 = '<div id="' + g + '"></div>';
var text2 = '<input data-checkbox="' + g + '" type="checkbox" style="display:none;"/><h3 data-header="' + g + '" style="display:inline-block;">Timer' + g + '  </h3><input data-input="' + g + '" type="text" style="display:none;"/>';
var text3 = '<span data-minutes="' + g + '">00</span>:<span data-seconds="' + g + '">00  </span><button data-start="' + g + '" >start</button><button data-stop="' + g + '" style="display:none;">stop</button><button data-clear="' + g + '" style="display:none;">clear</button>';
$('#header').append(text1);
$("#'"+g+"'").append(text2, text3);

Upvotes: 1

Views: 86

Answers (3)

OliverRadini
OliverRadini

Reputation: 6467

You're quite close to getting this right; the comments are trying to tell you that you aren't forming the selector correctly.

The selector for an id must be a string in the form:

'#id'

In your example you have too many ' symbols, so the id from your variable g will be in the string, but surrounded by variables. If g was test-id, you'd have the string:

"#'test-id'"

...and jQuery can't match that.

All you need to do is take out those quotes, here's how that might look:

var g = 'any-id';

var text1 = '<div id="' + g + '"></div>';
var text2 = '<span>Some other text</span>';

$('#header').append(text1);

$('#' + g).append(text2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="header">Header is here</div>

Upvotes: 1

Syed mohamed aladeen
Syed mohamed aladeen

Reputation: 6755

You just have a small mistake.

You need to try like this $("#"+g).append(text2, text3);

var g = "data";
var text1 = '<div id="' + g + '"></div>';
var text2 = '<input data-checkbox="' + g + '" type="checkbox" style="display:none;"/><h3 data-header="' + g + '" style="display:inline-block;">Timer' + g + '  </h3><input data-input="' + g + '" type="text" style="display:none;"/>';
var text3 = '<span data-minutes="' + g + '">00</span>:<span data-seconds="' + g + '">00  </span><button data-start="' + g + '" >start</button><button data-stop="' + g + '" style="display:none;">stop</button><button data-clear="' + g + '" style="display:none;">clear</button>';
$('#header').append(text1);
$("#"+g).append(text2, text3);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="header"></div>

Upvotes: 1

Simon
Simon

Reputation: 1081

This should be all you need:

$("#" + g)

The fact it's a string is already implied.

Upvotes: 1

Related Questions