desi123
desi123

Reputation: 19

Create dynamic id in html

I have my html and javascript code as below.

<!DOCTYPE html>
<html>
<head>
<style>
        #demo {
            border: 1px solid green;
            padding: 10px;
            margin: 20px;
        }
    </style>
    <style>
        #demo1 {
            border: 1px solid green;
            padding: 10px;
            margin: 20px;
        }
    </style>
<div id ="demo"></div>
<div id ="demo1"></div>
<script>
  var arr_args =  [["ab", "cd"], ["ef", "gh"]];
  var j, x = "";
  for (i=0; i<2; i++) {
    for (j=0; j< 2; j++) {
      x = x + arr_args[i][j] + "<br />"; 
     }
     if(i == 0) {
     document.getElementById("demo").innerHTML = x;
     x="";
     }
     if(i==1) {
        document.getElementById("demo1").innerHTML = x;
    }
  }


</script>
</html>

now instead of me creating demo and demo1 id's. I need the code t do it dynamically. Any help would be appreciated.

Upvotes: 1

Views: 3087

Answers (4)

StackSlave
StackSlave

Reputation: 10627

You probably really want to use a CSS class. .className in JavaScript.

//<![CDATA[
/* js/external.js */
var doc, html, bod, nav, mobile, M, I, S, Q, special, unspecial; // for use on other loads
addEventListener('load', function(){
doc = document; html = doc.documentElement; bod = doc.body; nav = navigator;
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
M = function(tag){
  return doc.createElement(tag);
}
I = function(id){
  return doc.getElementById(id);
}
S = function(selector, within){
  var w = within || doc;
  return w.querySelector(selector);
}
Q = function(selector, within){
  var w = within || doc;
  return w.querySelectorAll(selector);
}
special = function(str){
  return str.replace(/&/g, '&amp;').replace(/'/g, '&apos;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
unspecial = function(str){
  return str.replace(/&amp;/g, '&').replace(/&apos;/g, "'").replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
}
var out = I('output'), arr =  [['ab', 'cd'], ['ef', 'gh'], ['ij', 'kl', 'mn', 'op'], ['qr', 'st'], ['uv', 'wx', 'yz']], outerDiv, innerDiv;
arr.forEach(function(a){
  outerDiv = M('div'); outerDiv.className = 'demo';
  a.forEach(function(v){
    // no need for `special` in this case but you may have special characters to escape
    innerDiv = M('div'); innerDiv.innerHTML = special(v); outerDiv.appendChild(innerDiv);
  });
  output.appendChild(outerDiv);
});
}); // end load
//]]>
/* css/external.css */
*{
  box-sizing:border-box;
}
.demo{
  border: 1px solid green; padding: 10px; margin: 20px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
    <title>Test Template</title>
    <link type='text/css' rel='stylesheet' href='css/external.css' />
    <script type='text/javascript' src='js/external.js'></script>
  </head>
<body>
  <div id='output'></div>
</body>
</html>

Upvotes: 0

Shahab Arvin
Shahab Arvin

Reputation: 19

Try this:

<!DOCTYPE html>
<html>
<head>
    <style>
      [id^="demo"] {
            border: 1px solid green;
            padding: 10px;
            margin: 20px;
        }
    </style>
    <div id="section"></div>
<script>
var arr_args =  [["ab", "cd"], ["ef", "gh"], ["ij", "kl"]];
      
  arr_args.forEach(myFunction);

function myFunction(item, index) {
document.getElementById("section").innerHTML += "<div id=demo" + index + ">" + item[0] + "<br>" + item[1] + "<div>"; 
}

</script>
</html>

Upvotes: -1

Jon P
Jon P

Reputation: 19772

You can use querySelectorAll to select all divs starting with "demo", then use the corresponding index to update.

var arr_args = [
  ["ab", "cd"],
  ["ef", "gh"]
];
var j, x = "";
//Get all divs with an ID starting with demo
var divs = document.querySelectorAll("[id^=demo]");
for (i = 0; i < 2; i++) {
  for (j = 0; j < 2; j++) {
    x = x + arr_args[i][j] + "<br />";
  }
  
  //Update the corresponding div
  divs[i].innerHTML = x;  
  
  if (i == 0) {
    x = "";
  }
}
#demo1 {
  border: 1px solid green;
  padding: 10px;
  margin: 20px;
}

#demo {
  border: 1px solid green;
  padding: 10px;
  margin: 20px;
}
<div id="demo"></div>
<div id="demo1"></div>

Upvotes: 0

Nidhin Joseph
Nidhin Joseph

Reputation: 10227

You can use backticks as below to get the id as dynamic

document.getElementById(`demo${i == 0 ? '': i }`).innerHTML = x;

var arr_args = [
  ["ab", "cd"],
  ["ef", "gh"]
];
var j, x = "";
for (i = 0; i < 2; i++) {
  for (j = 0; j < 2; j++) {
    x = x + arr_args[i][j] + "<br />";
  }
  
  document.getElementById(`demo${i == 0 ? '': i }`).innerHTML = x;
  
  if (i == 0) {
    x = "";
  }
}
#demo1 {
  border: 1px solid green;
  padding: 10px;
  margin: 20px;
}

#demo {
  border: 1px solid green;
  padding: 10px;
  margin: 20px;
}
<div id="demo"></div>
<div id="demo1"></div>

Upvotes: 2

Related Questions