Append Element Into Element - javascript

It might sound stupid , but i didn't find the correct way to achieve this . I want to create an element(in our example a div element) and add to it the textarea value . In my example it seems that the element is created but i cant embed it into the #notesPosition . I achieve this with JQuery but i`am not sure whats the best way to do it with pure Javascript.
var notesPositionToAdd = document.getElementById('notesPosition');
var notesTextareaBtn = document.getElementById('btnAddNotes');
notesTextareaBtn.addEventListener('click', function(e) {
e.preventDefault();
var notesTextarea = document.getElementById('addNotesTextarea').value;
console.log(notesTextarea);
var newEl = document.createElement('div');
newEl.append(notesTextarea);
newEl.className += " col-lg-2";
console.log(newEl);
});
<div class="row ">
<div class="col-lg-4 col-md-4 col-sm-4 col-12 offset-md-8 ">
<form id="newNoteForm">
<div class="form-group offset-lg-6">
<i class="fa fa-times text-md-right " aria-hidden="true"></i>
<label for="addNotesTextarea">Add notes !</label>
<textarea class="form-control" id="addNotesTextarea" rows="3"></textarea>
<input class="btn btn-danger btn-sm" type="submit" value="Add" id="btnAddNotes">
</div>
</form>
</div>
</div>
<div class="row" id="notesPosition">
</div>

Hello
Check if this helps:
newEl.append(notesTextarea);
newEl.className += " col-lg-2";
console.log(newEl);
to:
newEl.append(notesTextarea);
newEl.className += " col-lg-2";
notesPositionToAdd.append(newEl);
console.log(newEl);
I hope it helped you!

If you want to addTextNode() then you can...
var div = document.createElement('div');
var txt = document.createTextNode('Whatever Text');
div.appendChild(txt);
alternatively
var div = document.createElement('div')
div.innerHTML = 'Whatever Text' // Whatever text parsed, <p>Words</p> is OK
alternatively
var div - document.createElement('div')
div.textContent = 'Whatever' // Not parsed as HTML

Related

Appended elements getting removed by HTML

I am trying to create a TO DO List application. In this application when I click submit button of the formlayer, a new eventcard with all the data should be appended in the events div.
function reveal() {
document.getElementById("layer1").style.display = "block";
document.getElementById("formlayer").style.display = "block";
}
function hide() {
document.getElementById("layer1").style.display = "none";
document.getElementById("formlayer").style.display = "none";
}
function addEvent() {
document.getElementById("layer1").style.display = "none";
document.getElementById("formlayer").style.display = "none";
let title = document.getElementById("ftitle").value;
let time = document.getElementById("ftime").value;
let desc = document.getElementById("fdesc").value;
// this will create the card
let card = document.createElement("div");
card.classList.add("eventcard");
//title div
let cardtitle = document.createElement("div");
cardtitle.classList.add("eventtitle");
cardtitle.innerHTML = title;
card.appendChild(cardtitle);
//time div
let cardtime = document.createElement("div");
cardtime.classList.add("eventtime");
cardtime.innerHTML = time;
card.appendChild(cardtime);
//desc div
let carddesc = document.createElement("div");
carddesc.classList.add("eventdesc");
carddesc.innerHTML = desc;
card.appendChild(carddesc);
// del button
let cardbtn = document.createElement("button");
cardbtn.classList.add("delete");
cardbtn.innerHTML = "Delete";
card.appendChild(cardbtn);
// adding card to events
document.getElementById("events").appendChild(card);
}
<div id="container">
<div id="title">To Do List</div>
<div id="events">
<div class="eventcard">
<div class="eventtitle">Meeting</div>
<div class="eventtime">10:00 AM</div>
<div class="eventdesc">The meeting regarding the discussion of company sales</div>
<button class="delete">Delete</button>
</div>
</div>
<div id="addbtn" onclick="reveal()">Add Events</div>
</div>
<div id="layer1"></div>
<div id="formlayer">
<div id="text">Event Details</div>
<form>
<label for="Title">Event Title: </label>
<input type="text" name="ftitle" id="ftitle"> <br><br>
<label for="Time">Event Time: </label>
<input type="text" name="ftime" id="ftime"> <br><br>
<label for="Desc">Event Description: </label>
<input type="text" name="fdesc" id="fdesc"> <br>
<button class="fbut" onclick="addEvent()">Submit</button>
<button class="fbut" onclick="hide()">Close</button>
</form>
</div>
However, when I fill up the details in the form and click submit button, the new eventcard gets appended in the events div for a split second and that too with all the correct information and styling, but then automatically gets deleted for some reason. Why it is getting deleted? I have also tried placing the script in <head> and after the </body> hoping that would work but it doesn't.
Could you guys please point out where I am doing wrong? Also I am doing this on Firefox browser (it might be related).
Add type="button" to your two buttons in the form, otherwise they will submit the form. This will cause a reload, so you lose your dynamic updates.
<button type="button" class="fbut" onclick="addEvent()">Submit</button>
<button type="button" class="fbut" onclick="hide()">Close</button>

How can I add elements in JS to certain divs

How do I put the created input into the other div in situation I presented below? If I introduce divs in js like this - '<div class="monday_input"><input type="button" class="remove_button" value="-" onclick="removeMon(this)" /></div>' removing the whole element is not working for some reason in this specific case. Answering the question. No I cannot create div in parent in html because input won't magically suit to created div . Please help me somehow, thank you!
HTML:
<div class="day">
<div class="day_info">
<p>Monday</p>
</div>
<div class="add">
<div class="button" onclick="add_monday()">
<i class="fas fa-plus" id="plus"></i>
</div>
</div>
<div style="clear:both"></div>
</div>
<div id="mon">
<div style="clear:both"></div>
</div>
JavaScript:
Function to adding:
function add_monday() {
if (monday_sub_count < 5) {
monday_sub_count++;
{
const mon = document.createElement('div');
mon.className = 'subcategory';
mon.innerHTML = '<textarea name="monday'+monday_id_count+'" placeholder="Type anything you want here" class="subcategory_text"></textarea><input type="button" class="remove_button" value="-" onclick="removeMon(this)" />';
monday_id_count++;
document.getElementById('mon').appendChild(mon);
}
}
}
Function to removing:
function removeMon(mon) {
document.getElementById('mon').removeChild(mon.parentNode);
monday_sub_count--;
monday_id_count--;
};
with your own HTML
function add_monday() {
var monday_sub_count = 0;
var a;
while (monday_sub_count < 5) {
a = '<div><textarea name="monday'+monday_id_count+'" placeholder="Type anything you want here" class="subcategory_text"></textarea><input type="button" class="remove_button" value="-" onclick="removeMon(this)" /></div>';
monday_sub_count++;
$('#mon').append(a);
}
}
Here is working, "proper" version of your code. I think your problem may come from over-complicating the removal process.
function add_monday()
{
let monday_count = 0;
// Use DocumentFragment for marginal optimizations
let fragment = new DocumentFragment();
while(monday_count < 5)
{
let monday = document.createElement('div');
monday.classList.add('subcategory');
let textarea = document.createElement('textarea');
textarea.classList.add('subcategory_text');
textarea.name = "monday_"+monday_count;
textarea.placeholder = "Type anything you want here";
let removeBtn = document.createElement('input');
removeBtn.type = "button";
removeBtn.classList.add('remove_button');
removeBtn.value = "-";
removeBtn.addEventListener('click', removeMon.bind(null, removeBtn));
monday.append(textarea, removeBtn);
fragment.appendChild(monday);
monday_count++;
}
document.getElementById('mon').appendChild(fragment);
}
function removeMon(button)
{
button.parentElement.remove();
}
I simplified your script a little and changed your name attributes: Instead of assigning individual names I simply gave all textareas the name monday[]. When posting this to a PHP page the values will be pushed into an array with the same name and in case you want to harvest the values with JavaScript, then this can be done easily too.
function add_monday(){
$("#mon").append('<div><textarea name="monday[]" placeholder="Type anything you want here"></textarea><input type="button" value="-"/></div>'.repeat(5))
}
$("#mon").on("click","input[type=button]",function(){$(this).parent(). remove()})
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div class="day">
<div class="day_info">
<p>Monday</p>
</div>
<div class="add">
<div class="button" onclick="add_monday()">
<i class="fas fa-plus" id="plus">click here to add fields</i>
</div>
</div>
<div style="clear:both"></div>
</div>
<div id="mon">
<div style="clear:both"></div>
</div>
And here a non-jQuery version:
const ad=document.querySelector(".alldays");
ad.innerHTML=
"Mon,Tues,Wednes,Thurs,Fri,Satur,Sun".split(",").map(d=>`
<div class="day">
<div class="day_info"><p>${d}day</p></div>
<div class="add">
<div class="button">
<i class="fas fa-plus" id="plus">click here to add fields</i>
</div>
</div>
<div style="clear:both"></div>
</div>
<div id="${d.toLowerCase().substr(0,3)}">
<div style="clear:both"></div>
</div>`).join("");
function add2day(el,n){
const wd=el.closest(".day"),
d=wd.querySelector("p").textContent.toLowerCase(),
html=`<textarea name="${d.toLowerCase()}[]" placeholder="Type anything you want here"></textarea><input type="button" value="-"/>`;
while (n--) {
let div= document.createElement("div");
div.innerHTML=html;
wd.nextElementSibling.appendChild(div);
}
}
ad.addEventListener("click",function(ev){
const el=ev.target;
switch(el.tagName){
case "INPUT": // remove field
el.parentNode.remove(); break;
case "I": // add new fields
add2day(el,3); break;
}
})
<div class="alldays"></div>
I extended the second script to make it work for any day of the week.

Append Content to HTML and Remove Appended Content When Click Button

The following code allows me to append new content to the div "users". However, I want to be able remove the appended content if the user clicks button.
The current code removes only the "remove" button when its clicked. However, I need to remove the entire appended code with the class "removeuser", in the beginning of the appended code.
Any help will be appreciated!
<div id="users"></div>
<script>
function adduser() {
count += 1;
$('#users').append('<div id="field'+ count +'" class="removeuser[]"><div
id="left"><div id="fieldname">user #'+ count +' Name:</div><div
id="field"><input id="user_name'+ count +'" name="user_name[]"' + '"
type="text" /></input></div><div id="clear"></div></div><div id="leftleft">
<div id="fieldname">user #'+ count +' Age</div><div id="field"><input
type="number" id="user_age'+ count +'" name="user_age[]"
style="width:50px;" min="0"></input></div><div id="clear"></div><br></div>
<div id="leftleft"><a href="javascript: void(0)" onclick="adduser(); return
false;"><div id="field" class="add"><div
style="position:relative;left:-4px;top:1px;">add another user +</div></div>
</a><br></div> <div id="leftleft"><a href="javascript: void(0)"
onclick="$(this).remove();" ><div id="deluser[]" class="add"><div
style="position:relative;left:-4px;top:1px;">-</div></div></a><br></div>
<div id="clear"></div></div>');
var no = document.getElementById("deluser");
no.onclick = function(){
$('#users .removeuser').$(this).remove();
};
</script>
From what I can tell this is might be the solution you're looking for (note not supported in all browser. See below for transpiled version)...
var count = 0;
adduser();
function adduser() {
$('#users').append(newUser(count))
count++;
}
function deluser(e) {
$(e.target).closest('.user-container').remove();
}
function newUser(count) {
var deleteButton = `
<div>
<a href="javascript: void(0)" onclick="deluser(event); return false;">
<div class="add delete-user" data>
<div style="position:relative;left:-4px;top:1px;">-</div>
</div>
</a>
<br>
</div>
`;
return `
<div class="user-container">
<div id="left">
<div class="fieldname">
user #${count} Name:
</div>
<div class="field">
<input id="user_name${count}" name="user_name[]" type="text" /></input>
</div>
<div id="clear"></div>
</div>
<div>
<div class="fieldname">
user #${count} Age
</div>
<div class="field">
<input type="number" id="user_age${count}" name="user_age[]" style="width:50px;" min="0"></input>
</div>
<div id="clear"></div><br>
</div>
<div>
<a href="javascript: void(0)" onclick="adduser(); return false;">
<div class="field" class="add">
<div style="position:relative;left:-4px;top:1px;">add another user +</div>
</div>
</a>
<br>
</div>
${count > 0 ? deleteButton : ""}
<div class="clear">
</div>
</div>
`;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="users"></div>
There area quite a few things wrong with your initial attempt though and I don't mean to be rude, but you should probably do more work learning the basics of HTML, JS and in this case jQuery. Treehouse is where I started out many years ago and think it is a great introduction to web development (Treehouse - front-end web development). That being said here are the most glaring issues...
Unique ids
id attributes must be unique per HTML document. As in, having id="leftleft" and then on another element in same document having id="leftleft" is invalid.
Missing closing bracket of function block }
HTML template strings
Honestly I don't know how you're able to read that HTML template string, but this is one of the issues front-end frameworks like React and Angular are meant to solve. Writing HTML templates like this will definitely introduce bugs and also drive you insane.
Instead or rewriting your whole program in React or Angular I would suggest using Template Literals and either using Webpack + babel to transpile your code to achieve browser support or for now just visit Babel repl and manually drop in your JS (with template literals) then replace with output code.
This is how the code would look after being transpiled through Babel, which would be supported in all browsers..
var count = 0;
adduser();
function adduser() {
$('#users').append(newUser(count));
count++;
}
function deluser(e) {
$(e.target).closest('.user-container').remove();
}
function newUser(count) {
var deleteButton = "\n <div>\n \n <div class=\"add delete-user\" data>\n <div style=\"position:relative;left:-4px;top:1px;\">-</div>\n </div>\n \n <br>\n </div>\n ";
return "\n <div class=\"user-container\">\n <div id=\"left\">\n <div class=\"fieldname\">\n user #".concat(count, " Name:\n </div>\n <div class=\"field\">\n <input id=\"user_name").concat(count, "\" name=\"user_name[]\" type=\"text\" /></input>\n </div>\n <div id=\"clear\"></div>\n </div>\n <div>\n <div class=\"fieldname\">\n user #").concat(count, " Age\n </div>\n <div class=\"field\">\n <input type=\"number\" id=\"user_age").concat(count, "\" name=\"user_age[]\" style=\"width:50px;\" min=\"0\"></input>\n </div>\n <div id=\"clear\"></div><br>\n </div>\n <div>\n \n <div class=\"field\" class=\"add\">\n <div style=\"position:relative;left:-4px;top:1px;\">add another user +</div>\n </div> \n \n <br>\n </div> \n ").concat(count > 0 ? deleteButton : "", "\n <div class=\"clear\">\n </div>\n </div>\n ");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="users"></div>
use something like this
$( '#users' ).empty();
You need to use following code
var no = $(".deluser"); // add class 'deluser' to each div
no.onclick = function(){
$('#users').empty();
};
I tried to illustrate your approach in another way, I hope it will help you.
var count = 0;
function addUser(i) {
var userBloc = '<li class="list-group-item" id="user'+i+'"> I am the user'+ i +
' <br><button class="btn btn-danger remove" data-count="'+i+'">Remove me</button><hr></li>';
return userBloc;
}
$('#add').click(function(){
$('#blocs').append(addUser(count));
$('#user'+count).fadeIn(activeRemove); //important to active remove event
count++;
});
function activeRemove(){
$.each($('button.remove'), function(i,item){
$(item).click(function(){
$('#user'+$(item).attr('data-count')).remove();
});
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="blocs" class="list-group"></div>
<button id="add">Add a another user</button>

How to append a div to a container

I implemented a chatroom by HTML and Javascript recently.
I don't know how to append the message(class="chat self") to the "chat-container" when I click the button "Send".
Here is the code:
<div id = "chat-container" class="chat-container">
<div class="chat friend">
<div class="user-photo"><img src="images/james.jpg"></div>
<p class="chat-message">How are you?</p>
</div>
<div class="chat self">
<div class="user-photo"><img src="images/curry.jpg"></div>
<p class="chat-message">Fine, thx!</p>
</div>
<div class="chat friend">
<div class="user-photo"><img src="images/james.jpg"></div>
<p class="chat-message">How old are you?</p>
</div>
</div>
<div class="chat-form">
<textarea id="myTextarea" placeholder="Type your message"></textarea>
<button onclick="sendMes()">Send</button>
</div>
My idea is like this:
<script>
function sendMes() {
var x = document.getElementById("myTextarea").value;
document.getElementById("demo").innerHTML = x;
vara data =
'<div class="chat self">
<div class="user-photo"><img src="images/curry.jpg"></d-wiv>
<p class="chat-message">Fine, thx!</p>
</div>';
data.chat-message = x;
document.getElementById("chat-container").appendChild(data);
}
</script>
I've read a lot of articles about HTML DOM, but they only tell how to change the .innerHTML...
I don't know how to create an div object with class="chat self", and set the object's chat-message to the value in the textarea.
Thanks a lot!
Instead of appending a DOM element to #chat-container you are simply appending a string to it (and that too seems to be malformed)
Maybe you should checkout W3School
A sample implementation of the sendMes() could be like
function sendMes() {
var message = document.getElementById("myTextarea").value // maybe try to sanitize it if you are sending it to server
var messageEl = document.createElement('p')
messageEl.innerHtml = message;
messageel.className = "chat-message"
var userImage = new Image()
userImage.src = "images/curry.jpg"
var imageContainer = document.createElement("div")
imageContainer.appendChild(userImage)
imageContainer.className = "user-photo"
var container = document.createElement("div")
container.appendChild(imageContainer)
container.appendChild(messageEl)
container.className = "chat self"
document.getElementById("chat-container").appendChild(container)
}

how to get a dom element from a template not html

here's the jsfiddle
at first try the script as is and then comment the last line and uncomment the one before it that will give me the functionality i want but with the wrong data, basically i want to grub a template and insert data into it and the insert it before another element in the page.
the problem is that the method that i'm using requires me to use an object or elementNode to insert it but after fetching the template i'm left with html wich result in an error :
Error: NOT_FOUND_ERR: DOM Exception 8
the html:
<section class="container well">
<header></header>
<section id="section">
<h4 id="heading">heading 4</h4>
<div id="div_1" class="divs">
file_1.jpg
<button class="btn btn-mini btn-danger pull-right">✖</button>
</div>
<div id="div_2" class="divs">
file_2.jpg
<button class="btn btn-mini btn-danger pull-right">✖</button>
</div>
<div id="div_3" class="divs">
file_3.jpg
<button class="btn btn-mini btn-danger pull-right">✖</button>
</div>
<div id="div_4" class="divs">
file_4.jpg
<button class="btn btn-mini btn-danger pull-right">✖</button>
</div>
<div class="clearfix">
<button class="btn btn-primary pull-right add">
Add items
</button>
</div>
</section>
<footer></footer>
</section>
<script type="template" id="template">
<div id="{{id}}">
{{fileName}}
</div>
</script>​
my javascript code:
$(document).on('click', '.add', function(e){
e.preventDefault();
e.stopPropagation();
target = document.getElementById($('.divs')[0].id);
template = document.querySelector('#template').innerHTML;
div = template
.replace(/{{id}}/g, '0')
.replace(/{{fileName}}/g, 'file_0');
//target.parentNode.insertBefore(document.createTextNode('AZERTY'), target);
target.parentNode.insertBefore(div, target);
});
the jsfiddle again and thanks in advance.
You cannot insert div, which is a string containing HTML code, into the DOM as if it were an element. Instead, you could create another div and set its innerHTML.
$(document).on('click', '.add', function(e){
e.preventDefault();
e.stopPropagation();
target = document.getElementById($('.divs')[0].id);
template = document.querySelector('#template').innerHTML;
div = template
.replace(/{{id}}/g, '0')
.replace(/{{fileName}}/g, 'file_0');
outerDiv = document.createElement('div');
outerDiv.innerHTML = div;
target.parentNode.insertBefore(outerDiv, target);
});
As noted by a comment on another answer, you may want to skip having a containing div within the template, as you will end up with two divs unnecessarily. Instead you could have simply
{{fileName}}
as the template and then
div = document.createElement('div');
div.id = '0';
div.innerHTML = template.replace(/{{fileName}}/g, 'file_0');
target.parentNode.insertBefore(div, target);
in the script. Another alternative is simply to insert the HTML string directly into the target:
target.innerHTML = div + target.innerHTML;
Here is an article - with several links and lots of good advice - about manipulating templates with jQuery:
How can I create an embeded HTML template using <script type="text/template"> using jquery
$('.add').on('click', function(e){
e.preventDefault();
e.stopPropagation();
target = document.getElementById($('.divs')[0].id);
template = document.querySelector('#template').html();
div = template.replace(/{{id}}/g, '0').replace(/{{fileName}}/g, 'file_0');
divtag = document.createElement('div');
divtag.innerHTML = div;
divtag.id = template.id;
target.parentNode.insertBefore(divtag, target);
}
This should work
here's the answer :
code:
$(document).on('click', '.add', function(e){
e.preventDefault();
e.stopPropagation();
target = document.getElementById($('.divs')[0].id);
template = document.querySelector('#template').innerHTML;
div = template
.replace(/{{id}}/g, '0')
.replace(/{{fileName}}/g, 'file_0.jpg');
new_div = document.createElement('div');
new_div.setAttribute('class', 'divs');
new_div.setAttribute('id', 'div_' + i);
new_div.innerHTML = div;
target.parentNode.insertBefore(new_div, target);
});
​
thanks to stuart.

Categories

Resources