Skip to content Skip to sidebar Skip to footer

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 =

Solution 1:

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


Solution 2:

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

Post a Comment for "JavaScript String Concatenation During Assignment"