Home > Net >  Jquery append to selector adding variable possible?
Jquery append to selector adding variable possible?

Time:09-21

I have code:

<p>aaa</p>
<p>bbb</p>
<p>ccc</p>

I would like to preprend a checkbox to every paragraph with:

$("p").prepend("<input type='checkbox' name='xxx' id='xxx' /><label for='test'>xxx</label></span>");

but instead of xxx I would need to enter some variable, like counter: var1, var2, var3... How do I do that?

CodePudding user response:

Use prepend as function:

$("p").prepend(function(index, htmlContent) {
    console.log(htmlContent); //aaa, bbb, ccc -> the content of selected element
    return "<input type='checkbox' name='xxx' id='" index "' /><label for='test'>xxx</label></span>";
});

CodePudding user response:

You search probably for so called "Template literals (Template strings)"

See please following snippet for an example of the usage.

For more information see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

CodePudding user response:

Try creating a string variable at first place in which you define the xxx variable value correctly, then use that string variable into the prepend! It should work fine

[edit]

const newXXX = "<input type='checkbox' name=" 'xxx new value' " id='xxx' /><label for='test'>xxx</label></span>"

$("p").prepend(newXXX)

You can use the any string concat method

  • Related