Doc Holiday
Doc Holiday

Reputation: 10254

JavaScript String Concatenation during Assignment

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".

Upvotes: 1

Views: 109

Answers (2)

Sampson
Sampson

Reputation: 268344

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

Upvotes: 4

ooo
ooo

Reputation: 1627

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

Upvotes: 0

Related Questions