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

6
  • 5
    What's your question? Are you looking for something like var test = '<button id="myButton_' + idNumber + '" class="myButtonsClass" type="button">testButton</button>'; Commented Nov 13, 2015 at 18:44
  • Context? What's your existing HTML? Existing Javascript? Commented Nov 13, 2015 at 18:44
  • This is html built by JS Commented Nov 13, 2015 at 18:45
  • show us your loop please. Commented Nov 13, 2015 at 18:45
  • 1
    If you're looking to just to concatenation, then yes. Looking at @Sampson's answer below, though, this is a much more proper way of handling this sort of thing. Commented Nov 13, 2015 at 18:50

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.