Getelementbyid When Id Is Dynamically Generated

getElementByID for Dynamically generated ID Elements

        <div> <img class="itemImage" id=Image001 src="/images/Image001"> </div>
<div id=ItemID001> 001 </div>
<div id=ItemName001> SomeNameOfItem001" </div>

<div> <img class="itemImage" id=Image002 src="/images/Image002"> </div>
<div id=ItemID002> 002 </div>
<div id=ItemName002> SomeNameOfItem002" </div>

<div> <img class="itemImage" id=Image003 src="/images/Image003"> </div>
<div id=ItemID003> 003 </div>
<div id=ItemName003> SomeNameOfItem003"> </div>

$(document).ready(function () {
$(".itemImage").click(function () {
var imgID = $(this).prop('id').replace("Image", "");
// you can directly use value imgID variable if its same. or you
//can use from ItemID inner html
var yourValue = $("#ItemID" + imgID).html();


How do I use getElementById on dynamically created inputs?

Okay so I found a solution. Apparently you can't use getElementById(checkboxId) to get the checkbox states. You have to create an array using getElementsByTagName("input") and afterwards itterate through this array while checking for inputs of the checkbox type.

var inputsArray = document.getElementsByTagName("input");
var ckbStateBuffer = new Array();

for (var i = 0; i < 3; i++)

if(inputsArray[i].type == "checkbox")




JSFiddle here:

A big thanks to Jarred Parr!

JavaScript - getElementById on dynamically added elements

You seem to have an extra space in the id string you are testing for. Since #{...} is an evaluated value, it shouldn't be in quotes in the first place.

Also, why use the back-tick string syntax here?

if (!!document.getElementById(`#\\3${playerId} `) == false) {

And, getElementById() already knows to look for id's so adding the # is going to search for elements that actually start with #.

Finally, if the element with that id does exist, it will return a "truthy" value that when converted to a Boolean, will convert to true, so there is no need to force a Boolean conversion (with !!) and then check to see if that is false.

That line can be rewritten to:

if (!document.getElementById(${playerId})) {

Accessing dynamically generated DIV using document.getElementByID

document.getElementById gets an element, by its ID, from the document.

You haven't added the div to the document yet, so it can't be found.

That said you already have the element! There's no need to search for it, in the document or anywhere else.

newDiv.innerHTML = html2;

getElementById Where Element is dynamically created and appended to DOM

I fixed my problem and I basically just mix jquery and javascript together. Yeah I know bad practice whatnot but for now it works flawlessly and that's what matters for the team.

So in short that's the end result. Nothing magic but it did it for me :

<script src="js/firstscript.js"></script>

var userCurrency = 'usd';

type: 'hidden',
id: 'userCurrency',
name: 'userCurrency',
value: userCurrency


//vanilla javascript code below
var amountCurrency = userCurrency;

How do I get a dynamically created ID?

Your problem is that id is unique and can only be assigned once to a element, like so:

<p id="paragraph"> This is legal </p>
<p id="paragraph"> This is illegal - It is no longer unique </p>

<p class="paragraph"> This is legal </p>
<p class="paragraph"> This is legal </p>

You can access the currently clicked class by using $(this) like so:

$('.paragraph').click(function() {
$(this).html('See, totally legal.');

See this example to see this in use.

Your solution needs to add an onclick() method to a button. This then gets the parent() form. You can then find() the class and get the val() from the form data.

Your form was also submitting the action. You need to have a <button> of type button so it does not submit the action. This must also be a class since it will not be unique if you're multiply creating them.

Here is a working example to just re-add your AJAX request too.

$(document).ready(function() {  $('.submit-btn').click(function() {    var elements = {      'userid': $(this).parent().find('.userid').val(),      'productid': $(this).parent().find('.productid').val(),      'collection': $(this).parent().find('.collection').val(),      'wish': $(this).parent().find('.wish').val()    };
console.log("User ID: " + elements.userid); console.log("Product ID: " + elements.productid); console.log("Collection: " + elements.collection); console.log("Wish: " + elements.wish);
// TODO: Add your AJAX request using these elements });});
button {  background: #0084ff;  border: none;  border-radius: 5px;  padding: 8px 14px;  font-size: 15px;  color: #fff;  cursor: pointer;}
<script src=""></script>
<!-- This will be generated by PHP -->
<form method='POST'> <input hidden class="userid input-box" value="1"> <input hidden class="productid input-box" value="1"> <input hidden class="collection input-box" value="1"> <input hidden class="wish input-box" value="1"> <button type="button" class="submit-btn btn my-2 my-sm-0 btn-outline-dark btn-sm"> Add to collection </button></form>
<!-- This will be generated by PHP --><br />
<form method='POST'> <input hidden class="userid input-box" value="2"> <input hidden class="productid input-box" value="2"> <input hidden class="collection input-box" value="2"> <input hidden class="wish input-box" value="2"> <button type="button" class="submit-btn btn my-2 my-sm-0 btn-outline-dark btn-sm"> Add to collection </button></form>

document.getelementById doesn't work on dynamically generated divs

Since you already creating the div in js, why not hold the reference then?

function makeDiv() {
var quizDiv=document.createElement("div");
return quizDiv;
function createInputBox(quizDiv,boxId) {
// var quizDiv = document.getElementById("quizDiv");
quizDiv.innerHTML = "<input type='text' id='" + boxId + "'>";
var quizDiv=makeDiv();

Dynamically generated html, document.getElementByID returns null

After figuring out that passing an <asp:button/> as a string wasn't going to work, I took an alternative approach.

In populateMemberTable()I added an href attribute to the first column in each row

                var href = true;              
foreach(DataColumn column in new_dt.Columns)
if (href)
href = false;
html.Append("<a href='/default.aspx?guid=" + Session["guid"] + "&membid=" + row[column.ColumnName] +"'>");


And then I saved the membId as a session variable in Page_Load()

    protected void Page_Load(object sender, EventArgs e)
//save guid ( as session variable
Session["guid"] = Request.QueryString["guid"];
var membId = Request.QueryString["membid"];
if (membId != null)
Session["membid"] = membId;


It might not be the most elegant solution, but it got me what I needed and was straightforward to implement. Thanks for the input everyone!

Related Topics

Leave a reply