Click event - add html element everytime i click - Pure js - javascript

Hello everyone i have probably a small problem and i don't know how to fix that , i need onclick event that every time i click it add html code , i don't wanna use innerHTML because its risky, this is the code:
button.addEventListener('click',function () {
const elements = `<div class="list-elem ${classList} data-id=${id}">
<div class="to-do-date">
<h3>${myDateString + ' ' + myTimeString}</h3>
</div>
<i class="fas fa-times" style="display: flex;"></i>
<div class="to-do-topic">
<h1>${topic.value}</h1>
</div>
<div class="to-do-text">
<p>${textarea.value}</p>
</div>
</div>`
toDoLists.appendChild(elements);
id++
})
if i use append() it works like this:
Append looks like this
And if i use appendChild() i have this error below:
TypeError: Argument 1 of Node.appendChild is not an object.
Probably i'm dumb and the fix way is easy, anyways i want to make it in pure JS without jquery.
I hope i can get help here , thanks :)

I think you must use insertAdjacentHTML function like below. Read more here
var button = document.getElementById('btn');
var toDoLists = document.getElementById('toDoLists');
var id = 1,
classList = "classList",
myDateString = "6 May 2018",
myTimeString = "21:56:13",
topic = {
value: 13
},
textarea = {
value: 131313
};
button.addEventListener('click', function() {
const elements = `<div class="list-elem ${classList} data-id=${id}">
<div class="to-do-date">
<h3>${myDateString + ' ' + myTimeString}</h3>
</div>
<i class="fas fa-times" style="display: flex;"></i>
<div class="to-do-topic">
<h1>${topic.value}</h1>
</div>
<div class="to-do-text">
<p>${textarea.value}</p>
</div>
</div>`
toDoLists.insertAdjacentHTML('beforeend', elements);
id++;
});
<button id="btn">Click Me!</button>
<div id="toDoLists"></div>

Here is a working example (with most of your code) of a way to append html after an element:
(See comments in my code)
// Code below to make a working example
var button = document.getElementById("button");
var toDoLists = document.getElementById("toDoLists");
var id = 1,
classList = "classList",
myDateString = "xx/xx/xxxx",
myTimeString = "hh:mm:ss",
topic = {
value: "Topic"
},
textarea = {
value: "Text in text area"
};
// Here below, your code modified
button.addEventListener('click', function() {
// Creates a div and fill it with the html you wanted
var elements = document.createElement("div");
elements.innerHTML = `<div class="list-elem ${classList} data-id=${id}">
<div class="to-do-date">
<h3>${myDateString + ' ' + myTimeString}</h3>
</div>
<i class="fas fa-times" style="display: flex;"></i>
<div class="to-do-topic">
<h1>${topic.value}</h1>
</div>
<div class="to-do-text">
<p>${textarea.value}</p>
</div>
</div>`;
toDoLists.appendChild(elements);
// id++ // Disabled because fixed values for example !
})
/* Some styling */
.list-elem {
border: 1px solid gray;
}
<button id="button">It's me, the button</button>
<br /><br />
<div id="toDoLists">Here is the to-do list:</div>
Hope it helps.

Related

Trying to make divs inside divs with a loop

I'm trying to make div's with a loop and my data and in this divs i would like to make at the same time some other div's i tryed something but i think this is the wrong way to do it it would be great if someone could show me a example to make something like this so that in the end it should look like this:
<div class="col-3 vehicleholder" id="THE ID">
<div class="vehicle-icon">
<i class="fas fa-car"></i> <-- The Icon
</div>
<div class="vehicle-information">
<div class="car-name">THE VEH MODEL</div>
<div class="numberplates">THE PLATENUMBERS</div>
</div>
</div>
let app = JSON.parse(parkedvehicle);
const vehiclelist = document.querySelector('div.row vehicles')
for (i = 0; i < app.length; i++) {
let vehicleholder = document.createElement('div');
vehicleholder.classList.add('col-3', 'vehicleholder');
let id = app[i].id;
vehicleholder.setAttribute('id', id);
const vehicleinfo = document.querySelector('div.col-3 vehicleholder')
let vehicleicondiv = document.createElement('div');
vehicleicondiv.classList.add('vehicle-icon');
const vehicleinfoicon = document.querySelector('div.vehicle-icon');
let vehicleicon = document.createElement('i');
vehicleicon.classList.add('fas', 'fa-car');
//
const vehicleinfotext = document.querySelector('div.col-3 vehicleholder')
let vehicleicondiv2 = document.createElement('div');
vehicleicondiv2.classList.add('vehicle-information');
const vehicletext = document.querySelector('div.vehicle-information')
let vehicleicondiv3 = document.createElement('div');
vehicleicondiv3.classList.add('car-name');
vehicleicondiv3.innerHTML = app[i].vehmodel;
const vehicletext2 = document.querySelector('div.vehicle-icon');
let text = document.createElement('div');
text.classList.add('numberplates');
text.innerHTML = app[i].numberplates;
vehiclelist.appendChild(vehicleholder);
vehicleinfo.appendChild(vehicleicondiv);
vehicleinfoicon.appendChild(vehicleicon);
vehicleinfotext.appendChild(vehicleicondiv2);
vehicletext.appendChild(vehicleicondiv3);
vehicletext2.appendChild(text);
So the easiest way to do so its to create a wrapper.
<div id="wrapper"></div>
then to use for loop and insert the HTML that way:
let wrapper = document.getElementById('wrapper')
let app = JSON.parse(parkedvehicle);
for (let car of app){
wrapper.innerHTML += `
<div class="col-3 vehicleholder" id="${car.id}">
<div class="vehicle-icon">
<i class="fas fa-car"></i>
</div>
<div class="vehicle-information">
<div class="car-name">${car.vehmodel}</div>
<div class="numberplates">${car.numberplates}</div>
</div>
</div>
`
}
so what i did, inside the wrapper innerHTML i used `` (template literals) so i can write HTML, any javascript i want to implement i wrapped in ${} and all of this inside the for loop. notice that i wrote: wrapper.innerHTML += so it can add the code block again and again.
this is a codepen for example:
https://codepen.io/Elnatan/pen/eYZYZey
hope it helped you.
Simplest way is to use template literals
For example (this goes in the for loop)
const HtmlCode =
`<div class="col-3 vehicleholder" id="${app[i].id}">
<div class="vehicle-icon">
<i class="fas fa-car"></i>
</div>
<div class="vehicle-information">
<div class="car-name">${app[i].VEH}</div>
<div class="numberplates">${app[i].plateNumbers}</div>
</div>
</div>`;
vehiclelist.innerHTML += HtmlCode;

How can I get direct text without a tag with jQuery

I've got an issue where I want to select (and replace) a string of text with no tags with jQuery. I need to retrieve the "us-east1-mp2 lobby", but it only selects the text with a span.
My code:
function fixServerLocation() {
setTimeout(function() {
if ($(".admin.chatLog").find(".section").length > 0) {
var section = ($(".admin.chatLog").find(".section"));
if (typeof section !== 'undefined') {
var chatMessages = document.querySelectorAll("[id^='chatMessage']");
if (typeof chatMessages !== 'undefined') {
$('.section [id^="chatMessage"]').children('div.details').children().css({
"color": "red",
"border": "2px solid red"
});;
//The code that I currently have to select the tag-less text. The styling is only to highlight it.
}
}
}
fixServerLocation();
}, 70);
}
fixServerLocation();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="chatMessage listItem first" id="chatMessage-us-east1-mp2-6668675">
<button class="expand small" type="button" tabindex="-1">+</button>
<div class="options right"></div>
<div class="details"><span class="time">2020-04-04 11:07</span>us-east1-mp2 lobby
<span><span class="username adminLookup">CommanderAnime</span></span>:
<span class="message ">Test</span></div>
</div>
How it currently looks when running the code:
I want to replace the "us-east1-mp2 lobby" with "Newark lobby". Thanks for any help
This is quite dangerous if your text is part of text attributes
NOTE: because I remove the event handler when I rewrite the HTML, you will need to delegate the button:
$("#someStaticContainerForTheChatMessages").on("click","button.expand",function() { whatever the button does })
$(function() {
const $chatMessages = $("[id^='chatMessage']");
if ($chatMessages.length > 0) {
$chatMessages.each(function(i, message) {
$('div.details', message).children().addClass("highlight")
message.innerHTML = message.innerHTML.replace("us-east1-mp2 lobby", "Newark lobby")
})
}
})
.highlight {
color: red;
border: 2px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="chatMessage listItem first" id="chatMessage-us-east1-mp2-6668675">
<button class="expand small" type="button" tabindex="-1">+</button>
<div class="options right"></div>
<div class="details"><span class="time">2020-04-04 11:07</span>us-east1-mp2 lobby<span><span class="username adminLookup">CommanderAnime</span></span>:
<span class="message ">Test</span></div>
</div>
If using jquery, you can easily achieve this by using javascript String.replace method:
const detailsHtml = $('.details').html()
const replacedContent = detailsHtml.replace('us-east1-mp2 lobby', 'Newark lobby')
$('.details').html(replacedContent)
Whats the idea: As this text isn't inside a tag, you need to get the whole div html as a string, and perform a replace. The first line returns the html content of .details as a string.
Then we perform the replace and use the same .html(value) method to set the new content.
Check the fiddle: https://jsfiddle.net/diogocosta/7wrmLog5/5/
const detailsHtml = $('.details').html()
const replacedContent = detailsHtml.replace('us-east1-mp2 lobby', 'Newark lobby')
$('.details').html(replacedContent)
//console.log(replacedContent)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="chatMessage listItem first" id="chatMessage-us-east1-mp2-6668675">
<button class="expand small" type="button" tabindex="-1">+</button>
<div class="options right"></div>
<div class="details"><span class="time">2020-04-04 11:07</span>us-east1-mp2 lobby
<span><span class="username adminLookup">CommanderAnime</span></span>:
<span class="message ">Test</span></div>
</div>

insert content into div from textarea Javascript

I am building a chat and i need to append content from the textarea to an inner div upon clicking send
<div class="inner" id="inner">
<div class="incoming" id="incoming">
<div class="them" id="them">Lorem
</div>
</div>
<div class="outgoing" id="outgoing">
<div class="me" id="me">Lorem ipsum
</div>
</div>
</div>
the button and textarea code is
<textarea class="input" id="input" placeholder="Message.."></textarea>
<a class="waves-effect waves-light" id="send-btn" >Send</a>
Javascript
var sendButton= document.getElementById('send-btn');
var textArea = document.getElementById('input');
var innerDiv= document.getElementById('inner');
var message=textArea.value;
sendButton.addEventListener('click', function(){
innerDiv.innerHTML=meMessage;
});
var meMessage= '<div class="outgoing" id="outgoing">'+
'<div class="me" id="me"></div></div>';
What i am trying to do is show the text value of the text area to the inner div called 'me' when i click send
and also get the value of the textarea to save it to a database. How can i achieve this
First of all you shouldn't create html elements manually since they would be XSS vulnerable and read about escaping mechanics to prevent malicious code being injected.
Try using document.createElement('div'); method to create div with valid innerText.
later use method:
innerDiv.appendChild(createdElement);
To append element.
You could create builder to build html elements you need and you have to htmlEncode text that will be inside of div element.
const sendButton = document.getElementById('send-btn');
const textArea = document.getElementById('input');
const innerDiv = document.getElementById('inner');
var message = textArea.value;
sendButton.addEventListener('click', function () {
const message = new MessageContainerBuilder().BuildMessage(textArea.value);
innerDiv.appendChild(message);
textArea.value = '';
});
function encodeHtmlEntity(input) {
var output = input.replace(/[\u00A0-\u9999<>\&]/gim, function (i) {
return '&#' + i.charCodeAt(0) + ';';
});
return output;
}
function MessageContainerBuilder() {
var createDivElement = function (classTest) {
var div = document.createElement('div');
var classAttr = document.createAttribute('class');
classAttr.value = classTest;
div.setAttributeNode(classAttr);
return div;
};
var createSpanElement = function (value, classTest) {
var span = document.createElement('span');
if (classTest) {
var classAttr = document.createAttribute('class');
classAttr.value = classTest;
span.setAttributeNode(classAttr);
}
span.innerText = encodeHtmlEntity(value);
return span;
};
this.BuildMessage = function (text) {
var divContainer = createDivElement('outgoing');
var messageSpan = createSpanElement(text, 'me');
divContainer.appendChild(messageSpan);
return divContainer;
};
}
<div id="inner">
<div class="incoming">
<div class="them">Lorem
</div>
</div>
<div class="outgoing">
<div class="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message..."></textarea>
<button class="waves-effect waves-light" id="send-btn">Send</button>
UPDATE: Extended snippet code. Removed Ids since they shouldn't be used there to create multiple message elements with same Id. Changed anchor to button.
You need to get the value of the textarea on click of the link
var sendButton = document.getElementById('send-btn');
var textArea = document.getElementById('input');
var innerDiv = document.getElementById('inner');
var message = textArea.value;
sendButton.addEventListener('click', function() {
innerDiv.innerHTML = `<div class="outgoing" id="outgoing">${textArea.value}
<div class="me" id="me"></div></div>`;
});
<div class="inner" id="inner">
<div class="incoming" id="incoming">
<div class="them" id="them">Lorem
</div>
</div>
<div class="outgoing" id="outgoing">
<div class="me" id="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message.."></textarea>
<a class="waves-effect waves-light" id="send-btn">Send</a>
You can use this. Youe message variable is not receiving the textarea value
var sendButton= document.getElementById('send-btn');
var innerDiv= document.getElementById('inner');
sendButton.addEventListener('click', function(){
innerDiv.innerHTML=innerDiv.innerHTML+'<div class="outgoing" id="outgoing">'+document.getElementById('input').value+
'<div class="me" id="me"></div></div>';
});
<div class="inner" id="inner">
<div class="incoming" id="incoming">
<div class="them" id="them">Lorem
</div>
</div>
<div class="outgoing" id="outgoing">
<div class="me" id="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message.."></textarea>
<a class="waves-effect waves-light" id="send-btn" >Send</a>
Maybe be replacing your js with that :
document.getElementById('send-btn').addEventListener('click',
function(){
var userInput = document.getElementById('input').value;
if(userInput) { document.getElementById('me').innerHTML += '<br>' + userInput; }
}
);
That should let you go a step forward... And good luck for saving to DB.
innerDiv.append(message)
instead of
innerDiv.innerHTML=message

Update inner text of div inside a variable

There is a small hmtml code attached to variable templ. Inside variable templ there is a div with id note-remarks I want to add list of span text something like
<small class="note-tag">tag1</small>
inside it. Where tag1 is dynamic text. These dynamic text is currently alerted as l. Selected tags are the tags selected while making comment.
var tmpl = `<div class="container mb-1">
{{date('m/d/Y')}}
<span class="text-gray pull-right">{{Auth::user()->name}}</span>
<p class="text-gray">
<strong>COMMENT</strong>
</p>
<div id="note-remarks">
</div>
</div>`;
function loadRecentNote(comment,selected_tags){
$('#recent_note').prepend(tmpl.replace("COMMENT", comment));
$.each(selected_tags, function( i, l ) {
alert(l)
});
}
var tmpl = `<div class="container mb-1">
{{date('m/d/Y')}}
<span class="text-gray pull-right">{{Auth::user()->name}}</span>
<p class="text-gray">
<strong>COMMENT</strong>
</p>
<div id="note-remarks"></div>
</div>`;
function loadRecentNote(comment, selected_tags) {
var $tmpl = $(tmpl.replace("COMMENT", comment));
$.each(selected_tags, function(i, l) {
$tmpl.find('#note-remarks').append('<small class="note-tag">' + l + '</small>')
});
$("#recent_note").prepend($tmpl);
}
loadRecentNote('comment', ["tag1", "tag2"]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="recent_note"></div>
Try this: You can append all selected tags in a variable and then replace it with html of noter-remarks
var tmpl = `<div class="container mb-1">
{{date('m/d/Y')}}
<span class="text-gray pull-right">{{Auth::user()->name}}</span>
<p class="text-gray">
<strong>COMMENT</strong>
</p>
<div id="note-remarks">
</div>
</div>`;
function loadRecentNote(comment,selected_tags){
$('#recent_note').prepend(tmpl.replace("COMMENT", comment));
var selectedText = '';
$.each(selected_tags, function( i, l ){
//alert(l);
selectedText += '<small class="note-tag">' + l + '</small>';
});
$('#recent_note #note-remarks').html(selectedText);
}
To achieve this you can use map() on the array of selected_tags to build a HTML string which you can then use to replace() a marker in the template; similar to how your logic is currently working for COMMENT. Try this:
var tmpl = `
<div class="container mb-1">
{{date('m/d/Y')}}
<span class="text-gray pull-right">{{Auth::user()->name}}</span>
<p class="text-gray">
<strong>COMMENT</strong>
</p>
<div id="note-remarks">REMARKS</div>
</div>`;
function loadRecentNote(comment, selected_tags) {
var remarksHtml = selected_tags.map(function(tag) {
return `<small class="note-tag">${tag}</small>`;
}).join('');
var html = tmpl.replace("COMMENT", comment)
html = html.replace("REMARKS", remarksHtml)
$('#recent_note').prepend(html);
}
loadRecentNote('Comment foo bar', ['tag #1', 'tag #2']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="recent_note"></div>
Select your element, identifying it uniquely and set it to the new value with ".text("arg")"
jQuery method:
$(".note-tag").text("updateText");

Append div in button on click Javascript

Hi how to append div inside button on click this is my JavaScript:
function addLoader() {
var div = document.createElement('div');
div.innerHTML = '<div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div>';
var test01 = document.createElement('button');
test01.appendChild(div);
console.log(test01);
}
I want to add innerHTML inside button tags on click
<button onclick="addLoader(this);">testt </button>
It must be like this when function is finish :
<button>testt <div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div> </button>
HTML
// Added id attribute
<button onclick="addLoader();" id = "test01">testt </button>
JS
function addLoader() {
var _div = document.createElement('div');
_div.innerHTML = '<div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div>';
//append _div to button
document.getElementById("test01").appendChild(_div);
}
Working jsfiddle
EDIT
This will append element to any button call addLoader on click
function addLoader(elem) {
var _div = document.createElement('div');
_div.innerHTML = '<div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div>';
elem.appendChild(_div);
}
Updated jsfiddle
var btn = document.getElementById("addLoader");
if (btn) {
btn.addEventListener('click', addLoader, false);
}
function addLoader() {
var div = document.createElement('div');
div.innerHTML = '<div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div>';
this.appendChild(div);
}
<button id="addLoader">Test</button>
You just need one more line of code. The variable test01 is created in memory but not added to the DOM. You must append this new element to the DOM (ie. document.appendChild(test01))

Categories