Dynamically Creating HTML Elements Using JavaScript

How to create an element dynamically in an html page using javascript?

there are two mistakes in your code
the first is that you used wrong "id" name div-1 instead of div1
also, innerText isn't a function

this is the code after the fix :)

<header>  <meta charset="utf-8"></header>
<body>
<button onclick="constructElement()">click</button>
<div id="div-1">
</div>
<script> function constructElement() { var elem = document.createElement("h6"); elem.innerText = "Dynamically added text." document.getElementById("div-1").appendChild(elem); } </script></body>

How to dynamically create these HTML elements using JS

You can use a for loop to append the HTML to the element of your choice. The i in the loop is the size of the elements received from the database

for(let i=1;i<10;i++){document.querySelector('.card-body').innerHTML+=`<div class="row" id="img_div">    <div class="col-12 col-sm-12 col-md-2 text-center">      <img src="http://placehold.it/120x80" alt="prewiew" width="120" height="80">    </div>    <div id="text_div" class="col-12 text-sm-center col-sm-12 text-md-left col-md-6">      <h4 class="product-name"><strong>Person`+i+`</strong></h4>      <h4>        <small>state</small>      </h4>      <h4>        <small>city</small>      </h4>      <h4>        <small>zip</small>      </h4>    </div>    <div class="col-12 col-sm-12 text-sm-center col-md-4 text-md-right row">    </div>  </div> `}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"><div class="card-body">  <!-- person -->  </div>

Generating dynamic HTML elements using Javascript alternatives?

You can use the template element.

To create an instance of the template element, use tmplElem.content.cloneNode(true).

function createUserCard(user) {
let userCardEle = userCard.content.cloneNode(true);
let elems = byName(userCardEle);
elems.first_name.innerText = user.first_name;
elems.last_name.innerText = user.last_name;
elems.score.innerText = user.score;
return userCardEle;
}

function byName (elem)
{
return new Proxy({}, {
get (_, prop) { return elem.querySelector(`[name=${prop}]`); }
});
}

// Test

document.body.appendChild(createUserCard({first_name: "John", last_name: "Smith", score: 1e+5}));
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">

<template id=userCard>
<div>
<h5 class="card-title">User</h5>
<dl class="row">
<dt class="col-sm-3">Name</dt>
<dd class="col-sm-9">
<span name=first_name></span>
<span name=last_name></span>
</dd>
<dt class="col-sm-3">Score</dt>
<dd class="col-sm-9"><span name=score></span></dd>
</dl>
</div>
</template>

Javascript help on dynamically creating html elements and populating the element onto the DOM

You just need to forEach over the array. Inside the callback, create a p, append it to the desired container, and set its textContent to the array element. No frameworks/libraries required:

const test = document.getElementById('test');const my_arr = ["test", "abc", 123];my_arr.forEach((item) => {  test.appendChild(document.createElement('p'))    .textContent = item;});
<h2>My First Web Page</h2><p>My first paragraph.</p><div id="test"></div>

HTML: Add elements dynamically using JS

You can use the .innerHTML += method wired up to an "Add Activity" button. Each time you click the button a new table row is added with the correct index numbers. Here is a fully working example - for the sake of simplicity and having only one file, I've included the javascript directly in the HTML code:

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Activity Log</title>
<script>

// Wait until the window finishes loaded before executing any script
window.onload = function() {

// Initialize the activityNumber
var activityNumber = 3;

// Select the add_activity button
var addButton = document.getElementById("add_activity");

// Select the table element
var tracklistTable = document.getElementById("tracklist");

// Attach handler to the button click event
addButton.onclick = function() {

// Add a new row to the table using the correct activityNumber
tracklistTable.innerHTML += '<tr><td>' + activityNumber + '</td><td><label>Activity Log: </label><br/><input type="text" name="actlog' + activityNumber + '" class="required"></td><td><label>Time: </label><br/><input type="time" name="time' + activityNumber + '" class="required"></td></tr>';

// Increment the activityNumber
activityNumber += 1;
}

}

</script>

</head>

<body>
<div class="container">
<div class="row">
<div class="leftcol">
<form name='mainForm' id='mainForm' method="get" action="#">
<fieldset>
<legend>Input Activity Logs</legend>
<table id="tracklist">
<tr>
<th colspan="3">Track List: </th>
</tr>
<tr>
<td>1</td>
<td><label>Activity Log: </label><br/><input type="text" name="actlog1" class="required"></td>
<td><label>Time: </label><br/><input type="time" name="time1" class="required"></td>
</tr>
<tr>
<td>2</td>
<td><label>Activity Log: </label><br/><input type="text" name="actlog2" class="required"></td>
<td><label>Time: </label><br/><input type="time" name="time2" class="required"></td>
</tr>
</table>
<input type="submit" />
</fieldset>
</form>
<button id="add_activity">Add Activity</button>
</div>
</div>
</div>
</body>
</html>

How to access and use a dynamically created html element with IDs in the DOM using Javascript

A couple of changes:

  1. You need to pass a parameter to the del() function. In this
    case, I modified your code to pass the click event. I then check the id of the clicked element in your if/else blocks.
  2. .strike() is a String function, but you are applying it to a DOM element. You need to grab the DOM text, apply .strike() to it, and set the innerHTML value to it.
  3. get is a keyword in javascript, I changed it to get1.

<body><div>    <h1>        <span id="cls">3</span> To-DOs</h1>    <input type="text" value="Enter A To-Do" id="input001" onclick="this.select()" onmouseout="this.style.transition = 0.5 + 's';"    />    <br />    <br />    <input type="button" value="Insert" id="button" onmouseout="document.getElementById('button').style.transition = 0.5 + 's';"     onclick="send()"></div><div>    <fieldset>        <legend>Your To-Do(s)</legend>        <p id="import"> </p>    </fieldset></div><script type="text/javascript">    var get1 = document.getElementById('import');    var no = 0;    var click = 0;    var input;    var count = new Array("one", "two", "three");    var count2 = new Array('a', 'b', 'c');    var me = 0;
document.getElementById('input001').addEventListener('keypress', function (e) { // Enter Key Listener for the input box! var key = e.which || e.keyCode; if (key == 13) { e.preventDefault(); send(); } })
function send() { input = input001.value;
if ((input == "Enter A To-Do") || (input == "")) { Alert.render("No To-Do Is Set!"); } else if ((input != "Enter A To-Do") || (input != "")) { if (no <= 2) { click++; no++;
var element = document.createElement('span'); element.innerHTML = no + " ." + input + " "; element.id = count[me];
var btnOne = document.createElement('button'); btnOne.innerHTML = 'x'; btnOne.id = count2[me]; btnOne.setAttribute("onclick", "del(event)");
window.elementTwo = element; window.btnTwo = btnOne;
get1.appendChild(elementTwo); get1.appendChild(btnTwo);
get1.innerHTML += "<br />" + "<br />"; input001.value = ""; me++; } else if (no == 3) { Alert.render("Your 'To-Do Activity' input Limit On Your List Is Reached!" + "<br />" + "You Can't Add More! :("); } } }
function del(ev) { if(ev.target.id == 'a'){
document.getElementById('one').innerHTML = document.getElementById('one').innerText.strike();
}else if(ev.target.id == 'b'){
document.getElementById('two').innerHTML = document.getElementById('two').innerText.strike();
}else if(ev.target.id == 'c'){
document.getElementById('three').innerHTML = document.getElementById('three').innerText.strike();; }}
</script></body></html>


Related Topics



Leave a reply



Submit