Skip to content Skip to sidebar Skip to footer

Add Html Elements Dynamically With Javascript Inside Div With Specific Id

Ok, people, I need your help. I've found some code here on Stackoverflow (can't find that link) which generate HTML code dynamically via JS. Here is code: function create(htmlStr)

Solution 1:

All you need to do is change the last line. This will add the created element as the last child of the div:

document.getElementById("generate-here").appendChild(fragment);     

This will add the created element as the first child of the div:

var generateHere = document.getElementById("generate-here");
generateHere.insertBefore(fragment, generateHere.firstChild);

You can also use innerHTML to just replace everything with new text (as you do in your create function). Obviously this one doesn't require you to keep the create function because you need an html string instead of a DOM object.

var generateHere = document.getElementById("generate-here");
generateHere.innerHTML = '<divclass="someclass"><ahref="www.example.com"><p>some text</p></a></div>';

Solution 2:

Step 1. Let's create a function to return us an ordered HTML listview. Note we are passing in an array of data:

functioncreateListView(spacecrafts){
    var listView=document.createElement('ol');
    for(var i=0;i<spacecrafts.length;i++)
    {
        var listViewItem=document.createElement('li');
        listViewItem.appendChild(document.createTextNode(spacecrafts[i]));
        listView.appendChild(listViewItem);
    }
    return listView;
}

Step 2. Then let's display our listview in your div:

document.getElementById("displaySectionID").appendChild(createListView(myArr));

Solution 3:

this is my solution example

function divHTML(img, d1, r1, r2){
    const newDiv = document.createElement("div");
    const newContent = `
    <imgsrc="`+img+`"width=50%><h1style="color:white">`+d1+`</h1><buttononclick="dom1.value='A'">A</button><i>`+r1+`</i><br><buttononclick="dom1.value='B'">B</button><i>`+r2+`</i><br><inputid="dom1"type="text"><hr>
    `;
    newDiv.innerHTML = newContent;
    const currentDiv = document.getElementById("div1");
    document.body.insertBefore(newDiv, currentDiv);
}

divHTML("https://images-cdn.kahoot.it/decf7162-f24b-464b-b2e7-2cca47ae0b42?auto=webp", "qual รจ la scrittura giusta?", "opzione 1", "opzione 2"
    );

Post a Comment for "Add Html Elements Dynamically With Javascript Inside Div With Specific Id"