1

I am building a collection of buttons that are each going to be assigned to a variable. In my loop I have some id's that I want to append to each button's id attribute:

var test = '<button id="myButton_" class="myButtonsClass" type="button">testButton</button>';

I want it to look like button id="myButton_123".

Sampson
  • 265,109
  • 74
  • 539
  • 565
Doc Holiday
  • 9,928
  • 32
  • 98
  • 151

2 Answers2

4

Avoid long strings, and use the methods provided to you by the DOM itself. Creating elements, and manipulating their content/attributes doesn't need to be difficult:

// This will hold our buttons, so we aren't thrashing the DOM
var fragment = document.createDocumentFragment();

// Lets cycle over a collection of ids
[ 23, 57, 92 ].forEach(function ( id ) {

    // Create a button, and get ready to manipulate it
    var button = document.createElement( "button" );

    // Set a few properties, and the content
    button.id = "myButton_" + id;
    button.textContent = "Test Button";
    button.className = "myButtonsClass";

    // Push this button into the fragment
    fragment.appendChild( button );    

});

// Now we touch the DOM once by adding the fragment
document.body.appendChild( fragment );

In modern ES6+ environments, you can use template literal strings for in situe interpolation:

var id = "73868CB1848A216984DCA1B6B0EE37BC";
var button = `<button id='myButton${ id }'>Click Me</button>`;

That being said, I would still encourage you to break the task down into smaller, more consumable portions, and use the DOM apis to construct the element(s).

Sampson
  • 265,109
  • 74
  • 539
  • 565
0

You could use the replace function:

var template = '<button id="myButton_#" class="myButtonsClass" type="button">testButton</button>';

for (var i=0; i<10, i++) {
   console.log(template.replace('#',i));
}
0x9BD0
  • 1,542
  • 18
  • 41