javascriptjqueryprepend

jQuery prepend() stringifies argument


I have the following code:

sections=$("section");
for(let i=0; i<sections.length; i++){
    let sectionTempCode=("<button id='").concat(i.toString()).concat("'>Toggle section view</button>");
    console.log(sectionTempCode)
    sections[i].prepend(sectionTempCode)
}

The intention is to add button tags to the HTML and display a button in the beginning of each . Instead, what I get is the code for the tag inside double quotes, which results in the code itself being displayed in my page:

"<button id='0'>Toggle section view</button>"

Solution

  • Use .each() and the Elements generator $(HTMLTag, {...properties})

    $("section").each((i, el) => {
    
      $("<button>", {
        prependTo: el,
        id: i+1,
        type: "button",
        text: "Toggle section view",
        click() {
          console.log(this.id);
        }
      });
    
    });
    <section></section>
    <section></section>
    <section></section>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>