简体   繁体   中英

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);

This should be all you need:

$("#" + g)

The fact it's a string is already implied.

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM