How to create divs dynamically using JavaScript? - javascript

I want to create my divs in a way to access my JSON data and display all every time I create a new div. I have my first div display information through my JSON. This is what I got so far:
document.addEventListener('DOMContentLoaded', function() {
function function_name(data) {
return {data: ['nombre','telefono'],pie: 'texto'};
}
function _data(info) {
return info;
}
(function() {
var obj = {
id: 'id',
nombre: 'pepe',
telefono: '6691296347'
};
var body = document.getElementsByTagName('body')[0];
var div = document.createElement('div');
var p = document.createElement('p');
var span = document.createElement('span');
var _p = document.createElement('p');
var _span = document.createElement('span');
var btn = document.createElement('button');
var p_ = document.createElement('p');
var span_ = document.createElement('span');
p_.textContent = 'ID: ';
div.appendChild(p_);
p_.appendChild(span_);
span_.textContent = obj.id;
body.appendChild(div);
data = JSON.stringify(_data(obj));
p.textContent = 'nombre: ';
div.appendChild(p);
p.appendChild(span);
span.textContent = obj.nombre;
_p.textContent = 'Telefono: ';
div.appendChild(_p);
_p.appendChild(_span);
_span.textContent = obj.telefono;
div.appendChild(btn);
btn.textContent = 'button';
btn.setAttribute("id","id");
btn.addEventListener('click',function (e) {
console.log(_data(obj));
});
})();
});

I do not know if the is a basic javascript way to do that ...but i use jquery to add data to every new div element
data = {"obj" : [{"name" : "John"}]}
Json that returns object
$.each(data.obj, function(i, message){
var htmlMessage = "";
htmlMessage += "<div>";
htmlMessage += "<p>";
htmlMessage += "<span>";
htmlMessage += message.name;
htmlMessage += "</div>";
htmlMessage += "</p>";
htmlMessage += "</span>";
$("#body")[0].innerHtml += htmlMessage;
});

You can create a custom function for creating elements. For example:
// creating elements function
function createEl(config){
config = config || {};
if(!config.type) throw new Error('config type required!');
var new_el = document.createElement(config.type);
// check text param
if(config.text) new_el.textContent = config.text;
// maybe check for other element attributes (id, class, etc)
// ...
return new_el;
}
// some code
// ...
var obj = {
id: 'id',
nombre: 'pepe',
telefono: '6691296347'
};
var body = document.getElementsByTagName('body')[0];
var div = createEl({ type: 'div' });
var p = createEl({ type: 'p', text: 'nombre: '});
var span = createEl({ type: 'span', text: obj.nombre});
// other elements
// ...
// and then append
p.appendChild(span);
div.appendChild(p);
body.appendChild(div);
// ...

Related

JavaScript adding event on element generated element with innerHtml

I want to add an event on an element does doesn't exist in the original HTML (created with innerHtml). When i click nothing happens.
const btnRemove = document.getElementById("remove");
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
service.innerHTML += `
<div class="v1">
<p class="v3-text">Mown Lawn <span id="remove">remove</span></p>
<p class="v3-dollar"><span>$</span>20</p>
</div>`;
sMow = false;
total += 20;
totalC();
}
});
btnRemove.addEventListener("click", function remove() {
alert("HELLO");
});
I want to add a click event on the element with id remove.
Another way to do that is creating the elements instead of use the HTML code and a later search. This maybe useful if you, for example, don't want to add an id to the remove tag
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
var div = document.createElement("div");
div.className = "v1";
service.appendChild(div);
var p1 = document.createElement("p");
p1.className = "v3-text";
div.appendChild(p1);
var p1Text = document.createTextNode("Mown Lawn ");
p1.appendChild(p1Text);
var p1Span = document.createElement("span");
p1Span.setAttribute("id", "remove");
p1Span.innerText = "remove";
p1Span.addEventListener("click", function remove() {
alert("HELLO");
});
p1.appendChild(p1Span);
var p2 = document.createElement("p");
p2.className = "v3-dollar";
p2.innerHTML = "<span>$</span>20";
div.appendChild(p2);
sMow = false;
total += 20;
totalC();
}
});
As you can see, creating the elements allow you do whatever you want with it. It's longer but you can use a helper function like this:
function appendTag(parent, tagName, className) {
var tag = document.createElement(tagName);
if (className)
tag.className = className;
parent.appendChild(tag);
return tag;
}
And rewrite as:
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
var div = appendTag(service, "div", "v1");
var p1 = appendTag(div, "p", "v3-text");
p1.appendChild(document.createTextNode("Mown Lawn "));
var p1Span = appendTag(p1, "span");
p1Span.setAttribute("id", "remove");
p1Span.innerText = "remove";
p1Span.addEventListener("click", function remove() {
alert("HELLO");
});
var p2 = appendTag(p1, "p", "v3-dollar");
p2.innerHTML = "<span>$</span>20";
sMow = false;
total += 20;
totalC();
}
});
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
service.innerHTML += `
<div class="v1">
<p class="v3-text">Mown Lawn <span id="remove">remove</span></p>
<p class="v3-dollar"><span>$</span>20</p>
</div>`;
sMow = false;
total += 20;
totalC();
}
const btnRemove = document.getElementById("remove");
btnRemove.addEventListener("click", function remove() {
alert("HELLO");
});
});
var btnremove = document.getElementById("remove");
write this before starting click event

Javascript function not looping properly over items

This is my JS that adds evenet listeners to every ideanode:
var ideanodes = [...document.querySelectorAll('.ideanode')];
ideaNodesListRefresh();
function ideaNodesListRefresh(){
ideanodes = [...document.querySelectorAll('.ideanode')];
console.log("refreshed")
ideanodes.forEach(ideanode => {
var maintxt = ideanode.querySelector(".maintext");
var titleArrow = ideanode.querySelector(".title-arrow");
var mainArrow = ideanode.querySelector(".maintxt-arrow");
var comments = ideanode.querySelector(".comments");
titleArrow.addEventListener('click', function() {
maintxt.classList.toggle("hidden");
mainArrow.classList.toggle("hidden");
if (comments.classList.contains("hidden")) {;
} else {
comments.classList.toggle("hidden");
};
});
mainArrow.addEventListener("click", function() {
comments.classList.toggle("hidden");
});
});
};
the function gets fired at the end of the creation of a new ideanode:
function createNeed(user) {
if (user==user1) {
var newNeed = document.createElement('div');
newNeed.className = "ideanode";
var newNeedHeader = document.createElement('div');
newNeedHeader.className = "ideanodeheader";
var newNeedHeaderText = document.createTextNode('Need');
newNeedHeader.appendChild(newNeedHeaderText);
newNeed.appendChild(newNeedHeader);
var newNeedContent = document.createElement('div');
newNeedContent.className = "content";
newNeed.appendChild(newNeedContent);
var needTitle = document.createElement('div');
needTitle.className="title";
var needTitleH3 = document.createElement('h2');
var titleText = document.createTextNode('Title');
needTitleH3.appendChild(titleText);
needTitleH3.setAttribute('onclick', 'this.focus();');
needTitleH3.setAttribute('contenteditable', 'True');
newNeedContent.appendChild(needTitleH3);
var downArrow0 = document.createElement('i');
downArrow0.classList = 'fas fa-sort-down title-arrow';
newNeedContent.appendChild(downArrow0);
var maintext = document.createElement('div');
maintext.classList = 'maintext hidden';
textareaMain = document.createElement("textarea");
textareaMain.className = "maintextinput";
textareaMain.setAttribute('placeholder', 'Text');
maintext.appendChild(textareaMain);
newNeedContent.appendChild(maintext);
var downArrow1 = document.createElement('i');
downArrow1.classList = 'fas fa-sort-down maintxt-arrow hidden';
newNeedContent.appendChild(downArrow1);
var comments = document.createElement('div');
comments.classList = "comments hidden";
textareaComments = document.createElement("textarea");
textareaComments.className = "commentsinput";
textareaComments.setAttribute('placeholder', 'Comments');
comments.appendChild(textareaComments);
newNeedContent.appendChild(comments);
newNeed.appendChild(newNeedContent);
var container = document.querySelector('#needsuser1');
var lastNeed = document.querySelector(".ideanode:last-child");
lastNeed.parentNode.insertBefore(newNeed, lastNeed.nextSibling);
ideaNodesListRefresh();
} else {
console.log("user2")
}
}
But when I add a new ideanode the function doesn't work properly and the eventlisteners only work for the newest ideanode.
This is a codepen of what I'm doing: https://codepen.io/ricodon1000/pen/PoPeXJL
I would like to simply add eventlisteners to the arrows of the new ideanode and have all of the arrows of all of the ideanodes work.

How to add an Id, value and onclick event to a dynamic generated div

i have to add onglets (dev) and affect them an id, value and onclick.
i tried by this way but is not working
function functionDeleteLevel(s1,s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
var formData = new FormData();
formData.append("valeur", "deleteLevel");
ajaxPost("/deleteLevel", formData, function (reponse) {
var data = JSON.parse(reponse);
data.forEach(function(level){
var newLi = document.createElement("li");
newLi.value = level.level;
newLi.id = "levelId_"+level.level;
newLi.innerHTML = 'onclick="functionSelectedLevel(this.id)"';
newLi.innerHTML = '<a data-toggle="tab">Niveau'+level.level+'</a>';
s2.appendChild(newLi);
});
});
}
you can use
newLi.addEventListener('click', function() {functionSelectedLevel(this.id);})
or
newLi.onclick = function() {functionSelectedLevel(this.id);};
or - with a bit of a change to functionSelectedLevel
newLi.addEventListener('click', functionSelectedLevel)
or
newLi.onclick = functionSelectedLevel;
functionSelectedLevel would then be
functionSelectedLevel() {
// here, the value of this is the element that was clicked
do things with this.id
}

how to create several buttons dynamically in for loop

Here id my code. I want to append 4 buttons inside the specific div. In the other words, I want to put these 4 buttons inside ''. Now it works but they are not inside the div.
getmyItems function is a function that contains an array of information like: title, description , age ,... .
Help
getmyItems(param, function(data) {
var mtItem = JSON.stringify(data);
myItem = JSON.parse(mtItem);
var Item = document.getElementById('myItems');
for (var i = 0; i < myItem.results.length; i++) {
var buffer = "";
buffer += '<div class="act-time">';
buffer += '<div class="activity-body act-in">';
buffer += '<span class="arrow"></span>';
buffer += '<div class="text">';
buffer += '<p class="attribution">';
buffer += ''+myItem.results[i].title+'';
buffer += myItem.results[i].description;
buffer += '</p>';
buffer += '</div>';
buffer += '</div>';
buffer += '</div>';
var div = document.createElement('div');
div.innerHTML = buffer;
//var elem = div.firstChild;
Item.appendChild(div);
var btn = document.createElement('input');
btn.setAttribute('type', 'button');
btn.setAttribute('class', 'btn btn-danger');
btn.value = "Delete";
btn.onclick = (function(i) {
return function() {
var c=confirm('Are you Sure? ');
if (c==true)
doDelete(myItem.results[i].item_id);
};
})(i);
Item.appendChild(btn);
var show_btn=document.createElement('input');
show_btn.setAttribute('type','button');
show_btn.setAttribute('class','btn btn-primary');
show_btn.value="ShowInDetail";
show_btn.onclick=(function(i){
return function(){
showInDetail(myItem.results[i]);
window.location='showInDetail.html';
};
})(i);
Item.appendChild(show_btn);
var extend_btn=document.createElement('input');
extend_btn.setAttribute('class','btn btn-warning');
extend_btn.setAttribute('type','button');
extend_btn.value="Extend";
extend_btn.onclick=(function(i){
return function(){
extendItem(myItem.results[i]);
window.location='extendItem.html';
};
})(i);
Item.appendChild(extend_btn);
var bookmark=document.createElement('input');
bookmark.setAttribute('type','button');
bookmark.setAttribute('class','btn btn-primary');
bookmark.value='Bookmark';
bookmark.onclick=(function(i){
return function(){
var p={user_id:localStorage.getItem('user_id')};
window.localStorage.setItem('this_item_id', myItem.results[i].item_id);
getBookmarks(p, function(d){
var bk=JSON.stringify(d);
bk=JSON.parse(bk);
if(bk.results){
var l=0;
for(var j in bk.results){
if(bk.results[j].item_id==localStorage.getItem('this_item_id')){
removeBookmark(bk.results[j]);
l=1;
}
}if(l==0){
addBookmark(myItem.results[i]);
}
}else{
addBookmark(myItem.results[i]);
}
});
};
})(i);
Item.appendChild(bookmark);
//document.getElementById(i).appendChild(btn);
}
});
In what specific div do you want them? So far, in this way the four buttons are inside the myItens div see in the fiddle and in the code below.
var getmyItems = function(data) {
var item = document.getElementById('myItems');
for (var i = 0; i < data.length; i++) {
var result = data[i];
// creation of the buffer outer div
var buffer = document.createElement('div');
buffer.className = 'act-time';
//creation of de activity-body
var activity = document.createElement('div');
activity.className = 'activity-body act-in';
//creation of the first span
var arrow = document.createElement('span');
arrow.className = 'arrow';
//creation of the most inner div
var textDiv = document.createElement('div');
textDiv.className = 'text';
//creation of the content of the most inner div
var attribution = '';
attribution += '<p class="attribution">';
attribution += '' + result.title + '';
attribution += result.description;
attribution += '</p>';
//initialize the text div
textDiv.innerHTML = attribution;
//put the arrow span inside the activity div
activity.appendChild(arrow);
// put the text div inside the activity div
activity.appendChild(textDiv);
//put the activity inside the buffer div
// each time appendChild is applied the element is attach tho the end of the target element
buffer.appendChild(activity);
var div = document.createElement('div');
div.appendChild(buffer);
item.appendChild(div);
var btn = document.createElement('input');
btn.setAttribute('type', 'button');
btn.setAttribute('class', 'btn btn-danger');
btn.value = "Delete";
btn.onclick = (function(i) {
return function() {
var c = confirm('Are you Sure? ');
if (c === true) {
//do something;
};
};
})(i);
// now that all div are created you can choose which div you want to put the button inside.
// in this I chose the buffer.
buffer.appendChild(btn);
var showBtn = document.createElement('input');
showBtn.setAttribute('type', 'button');
showBtn.setAttribute('class', 'btn btn-primary');
showBtn.value = "ShowInDetail";
showBtn.onclick = (function(i) {
return function() {
window.location = 'showInDetail.html';
//do something
};
})(i);
// button is append to the end of the buffer
buffer.appendChild(showBtn);
var extendBtn = document.createElement('input');
extendBtn.setAttribute('class', 'btn btn-warning');
extendBtn.setAttribute('type', 'button');
extendBtn.value = "Extend";
extendBtn.onclick = (function(i) {
return function() {
window.location = 'extendItem.html';
//do something
};
})(i);
// button is append to the end of the buffer
buffer.appendChild(extendBtn);
var bookmark = document.createElement('input');
bookmark.setAttribute('type', 'button');
bookmark.setAttribute('class', 'btn btn-primary');
bookmark.value = 'Bookmark';
bookmark.onclick = (function(i) {
return function() {
var p = { user_id: localStorage.getItem('user_id') };
window.localStorage.setItem('this_item_id', myItem.results[i].item_id);
//do something
};
})(i);
// button is append to the end of the buffer
buffer.appendChild(bookmark);
}
};
var myItem = [{ title: 'person', description: 'familyName' }, { title: 'ohterPerson', description: 'otherFamilyName' }];
getmyItems(myItem);

How to run a nested javascript function?

I am new to object orientated programming in javascript and am trying to understand some functions in a project I am working on.
How would I call/run the internal function (the one listed 'this.getFieldset = function() {') to execute?
function Fieldset() {
this.id = "";
this.content = document.createElement("DIV");
this.content.id = "content";
this.title = "Title";
this.getFieldset = function() {
var div = document.createElement("DIV");
div.id = this.id;
var span = document.createElement("SPAN");
var fieldset = document.createElement("DIV");
fieldset.id = "fieldset";
var header = document.createElement("DIV");
header.id = "header";
span.appendChild(document.createTextNode(this.title));
header.appendChild(span);
div.appendChild(header);
div.appendChild(this.content);
div.appendChild(fieldset);
return div;
}
}
var myFieldset = new Fieldset();
myFieldset.getFieldset();
First you should create an instance of Fieldset, then you'll be able to call its functions (called methods):
var myFieldset = new Fieldset();
myFieldset.getFieldset();
function Fieldset() {
this.id = "";
this.content = document.createElement("DIV");
this.content.id = "content";
this.title = "Title";
this.getFieldset = function() {
var div = document.createElement("DIV");
div.id = this.id;
var span = document.createElement("SPAN");
//var fieldset = document.createElement("DIV");
//fieldset.id = "fieldset";
var header = document.createElement("DIV");
header.id = "header";
span.appendChild(document.createTextNode(this.title));
header.appendChild(span);
div.appendChild(header);
div.appendChild(this.content);
div.appendChild(fieldset);
window.alert("test");
return div;
}
//add call to run function
this.getFieldset();
}

Categories

Resources