Reputation: 1287
I am a newbie to Jquery and trying to do the following.
I have an ID of an element which is generated by concatenation of a variable string. I need to select that element with this generated ID using JQuery. Please see below for more info.. Lets say I have elements with IDs as follows in a html Page
ID1=Test_A_element
ID2=Test_B_element
ID3=Test_C_element
ID4=Test_D_element
I have a string variable (x) that contains A or B or C or D. I will generate the ID of this element by simple concatenation as follows
ID="Test_"+x+"_element";
I need to select the correct Element using Jquery.
Upvotes: 1
Views: 53
Reputation: 32804
Check this page for more details about jQuery selectors: http://www.w3schools.com/jquery/jquery_ref_selectors.asp.
Or the more detailed official page: https://api.jquery.com/category/selectors/.
In your particular case, you can select an element by id with the following construction: jQuery("#"+ID)
, or $("#"+ID)
.
Upvotes: 0
Reputation: 1074335
Using jQuery:
var jQuerySet = $("#" + ID);
Using the DOM:
var elem = document.getElementById(ID);
Live Example:
var ID =
"Test_" +
String.fromCharCode(65 + Math.floor((Math.random() * 4))) +
"_Element";
$("<p>").html("The ID is " + ID).appendTo(document.body);
$("#" + ID).css("color", "blue");
<div id="Test_A_Element">Test A</div>
<div id="Test_B_Element">Test B</div>
<div id="Test_C_Element">Test C</div>
<div id="Test_D_Element">Test D</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Upvotes: 2