add a button using javascript to an existing DIV - javascript

On my page I have:
<div id='something'></div>
and I want to append this type of 'button' to it using JS:
<span class="picon-p-add-news"></span>Read more news
I tried to use document.createElement but I'm not sure how to make it not just append it as text. How do I do this ?

Something like this, where you can pass your element ID and URL through function arguments.
<!DOCTYPE html>
<html>
<head>
<script>
function appendButton(elementId, url){
var buttonEl = document.createElement("a");
buttonEl.href = url;
var buttonTextEl = document.createElement("span");
buttonTextEl.className = "picon-p-add-news";
buttonTextEl.innerText = "Read more news";
buttonEl.appendChild(buttonTextEl);
document.getElementById(elementId).appendChild(buttonEl);
}
</script>
</head>
<body>
<div>
<button id="button">Click to add</button>
<div id='something'></div>
</div>
<script>
document.getElementById("button").addEventListener('click', () => appendButton("something", "/news_events/"));
</script>
</body>
</html>

Use document.createElement to create the specified HTML elements. Then you can append those to your #something root element using Node.appendChild function. You can also use Element.innerHTML to gets or sets the HTML markup contained within the element.
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node.
const something = document.getElementById('something');
// creating the span element, then add a class attribute
const span = document.createElement('span');
span.setAttribute('class', 'picon-p-add-news');
span.innerHTML = 'span'; // some text to improve visualization
// create the anchor element with the href attribute
const a = document.createElement('a');
a.setAttribute('href', '/news_events/');
// append the span element inside the <a>
a.appendChild(span);
a.innerHTML += 'anchor'; // add extra text for display
// add the <a> element tree into the div#something
something.appendChild(a);
#something {
border: 1px solid;
text-align: center;
font-size: 2rem;
}
#something > a {
padding: 8px;
}
.picon-p-add-news {
background: red;
padding: 0 4px;
}
<div id="something"></div>

Like this? You can use the innerHTML attribute to add HTML inside of an Element
document.getElementById("something").innerHTML += '<span class="picon-p-add-news"></span>Read more news';
<div id='something'></div>
Or, if you created this as an Element with createElement, you can use appendChild:
let a = document.createElement("a");
a.setAttribute("href", "/news_events/");
let span = document.createElement("span");
span.setAttribute("class", "picon-p-add-news");
a.appendChild(span);
a.innerHTML += "Read more news";
document.getElementById("something2").appendChild(a);
<div id="something2"></div>

1) Create a element:
var aEl = document.createElement('a');
aEl.href = "/news_events/"
2) Create span element:
var spanEl = document.createElement('span');
spanEl.classList.add('picon-p-add-news');
3) Append span element to a element
aEl.appendChild(spanEl);
4) Insert text in a element
aEl.insertAdjacentText('beforeend','Read more news');
5) Append whole a tree to you div
var divEl = document.getElementById('something');
divEl.appendChild(aEl);

<html>
<head>
<style>
#myDIV {
border: 1px solid black;
margin-bottom: 10px;
}
</style>
</head>
<body>
<p>Click the button to create a P element with some text, and append it to DIV.</p>
<div id="myDIV">
A DIV element
</div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var para = document.createElement("P");
var t = document.createTextNode("This is a paragraph.");
para.appendChild(t);
document.getElementById("myDIV").appendChild(para);
}
</script>
</body>
</html>
Give something like this a try: I used https://www.w3schools.com/jsref/met_document_createelement.asp for reference.

Related

CSS Not Applied to Node Added by JS appendChild

My html:
<div id=Info>
<p>Id: <span>001</span></p>
</div>
My CSS:
#Info p {
font-weight: bold;
}
#Info span {
font-weight: normal;
}
My JS code:
var pElement = document.createElement('p');
var spanElement = document.createElement("span");
var elementValue1 = document.createTextNode("Id: ");
var elementValue2 = document.createTextNode("003");
spanElement.appendChild(elementValue1);
pElement.appendChild(elementValue2);
pElement.appendChild(spanElement);
document.querySelector('#Info').appendChild(pElement);
CSS style applied correctly to the line:<p>Id: <span>001</span></p> from html file. But somehow, CSS style is not applied to the node added by appendChild from JS file. I couldn't figure out why.
I'm new to html/CSS/JS, any help would be appreciated!
Thanks!
It looks like the div id is not match between your html and the css.
In the html, the id=Info should be id="bookInfo"
Is seems to be qworking perfectly fine, but there are multiple issues in shared code.
CSS is referring to #bookInfo as opposed to #Info
You are appending elementValue1 to spanElement as opposed to elementValue2.
Let's look at fixed code:
var pElement = document.createElement('p');
var spanElement = document.createElement("span");
var elementValue1 = document.createTextNode("Id: ");
var elementValue2 = document.createTextNode("003");
spanElement.appendChild(elementValue2);
pElement.appendChild(elementValue1);
pElement.appendChild(spanElement);
document.querySelector('#Info').appendChild(pElement);
#Info p {
font-weight: bold;
}
#Info span {
font-weight: normal;
}
<div id=Info>
<p>Id: <span>001</span></p>
</div>
not a good way to do it but here is your code:
https://jsfiddle.net/r6j31zhL/
<html>
<body>
<div id="Info">
<p>Id: <span>001</span></p>
</div>
</body>
</html>
<style>
#Info p {
font-weight: bold;
}
#Info span {
font-weight: normal;
}
</style>
<script>
var pElement = document.createElement('p');
var spanElement = document.createElement("span");
var elementValue1 = document.createTextNode("Id: ");
var elementValue2 = document.createTextNode("003");
spanElement.appendChild(elementValue2);
pElement.appendChild(elementValue1);
pElement.appendChild(spanElement);
document.querySelector('#Info span').appendChild(pElement);
</script>

When adding elements and buttons to a div, how can each button remove itself?

I have a script that can add paragraphs to a div. These paragraphs have some text and a delete button in them. This delete button should be able to delete the paragraph its in including its text (so delete the whole paragraph), but it doesn't.
var elementCounter2 = 0;
function addElement2() {
elementCounter2++;
var p = document.createElement("p");
var node = document.createTextNode("This is element number " + elementCounter2);
p.setAttribute("id", "p" + elementCounter2);
p.appendChild(node);
p.innerHTML += ' <button id="del' + elementCounter2 + '" onclick="deleteElement2();">Delete this element.</button>';
document.getElementById("elements2").appendChild(p);
}
function deleteElement2() {
var p = document.getElementById("p" + elementCounter2);
var btn = document.getElementById("del" + elementCounter2);
//Button sees its own id and look for the corresponding p id, then deletes the paragraph.
}
.borderful {
border: solid 1px black;
margin: 10px;
padding: 10px;
}
<div class="borderful">
<p>Here is the second part</p>
<p>You can add elements here.</p>
<p>You can delete these aswell but differntly.</p>
<button onclick="addElement2();">Add an element.</button>
<div id="elements2"></div>
</div>
You can setup an event listener on each newly created paragraph (ditching the inline code) and forget about the counter (kept here to show the code working)
var elementCounter2 = 0;
function addElement2() {
elementCounter2++;
var p = document.createElement("p");
var node = document.createTextNode("This is element number " + elementCounter2);
p.setAttribute("id", "p" + elementCounter2);
p.appendChild(node);
p.innerHTML += ' <button>Delete this element.</button>';
document.getElementById("elements2").appendChild(p);
var el = document.getElementById("p" + elementCounter2);
el.addEventListener("click", deleteElement2, false);
}
function deleteElement2() {
this.remove()
}
.borderful {
border: solid 1px black;
margin: 10px;
padding: 10px;
}
<div class="borderful">
<p>Here is the second part</p>
<p>You can add elements here.</p>
<p>You can delete these aswell but differntly.</p>
<button onclick="addElement2();">Add an element.</button>
<div id="elements2"></div>
</div>
This should work
var elementCounter2 = 0;
function addElement2() {
elementCounter2++;
var p = document.createElement("p");
var node = document.createTextNode("This is element number " + elementCounter2);
p.setAttribute("id", "p" + elementCounter2);
p.appendChild(node);
p.innerHTML += ' <button id="del' + elementCounter2 + '" onclick="deleteElement2(this);">Delete this element.</button>';
document.getElementById("elements2").appendChild(p);
}
function deleteElement2(caller) {
// caller = button
document.getElementById("del" + caller.id.substr(3)).parentNode.remove();
}
.borderful {
border: solid 1px black;
margin: 10px;
padding: 10px;
}
<div class="borderful">
<p>Here is the second part</p>
<p>You can add elements here.</p>
<p>You can delete these aswell but differntly.</p>
<button onclick="addElement2();">Add an element.</button>
<div id="elements2"></div>
</div>
A simple approach is referring to the paragraph as a parent element instead of worrying how to reference it directly.
function deleteElement2() {
this.parentElement.remove();
}
However, adding the button as
p.innerHTML += ' <button id="del'+ elementCounter2 +'" onclick="deleteElement2();">Delete this element.</button>';
Is not a good practice since you are adding HTML element in Javascript, when you can go about doing this in Javascript only.
To learn more about your original question or how to do this in JS, refer to this very similar example given by CS50W lecture on YouTube: https://youtu.be/ZRV7JCXAFTs?t=2486

How to set textarea value to a hero text?

I'm trying to create a webpage. But it's main is this. If, somebody types something to the textarea, get it's value maybe with javascript, and display it in a hero text. Is it possible?
* {
margin: 0;
padding: 0;
}
h1 {
margin-left: 500px;
}
<textarea id="input"></textarea>
<h1 id="hero_text"></h1>
<button class="test" id="test">Enter</button>
Let's assume the text that of the hero image is in this:
<h1 id='hero_text'></h1>
And that your text area is:
<textarea id='input'></textarea>
Then you can use the textarea's onchange event to track when the user changes the text in the textarea, and update the hero text accordingly:
EDIT: To track changes while the user is typing (not after they de-select the textarea, use oninput instead of onchange).
var h1 = document.getElementById('hero_text');
var textarea = document.getElementById('input');
textarea.oninput = function() {
//note that inside this event handler, 'this' points to the textarea
h1.innerHTML = this.value;
}
Edit 2: Here's a snippet that's based on the code you just provided:
var h1 = document.getElementById('hero_text');
var textarea = document.getElementById('input');
var btn = document.getElementById('test');
btn.onclick = function() {
//note that inside this event handler, 'this' points to the button
h1.innerHTML = textarea.value;
}
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
</head>
<body>
<style>
*
{
margin: 0;
padding: 0;
}
h1
{
margin-left: 500px;
}
</style>
<script src="test.js"></script>
<textarea id="input"></textarea>
<h1 id="hero_text"></h1>
<button class="test" id="test">Enter</button>
</body>
</html>

How to add multiple div dynamically with append child having different id?

I am trying to add div on clicking add button.
on clicking add button the div is created with the
class name ui modal and
id test.
For multiple div created the same id gets added.
I need to give different ID for Each additionally added div.
How can I generate different ID using append child.
Also I need to get the tree structure with parent child and sibling node.
function add_div(){
var div = document.createElement('div');
document.body.appendChild(div);
div.className = 'ui-modal';
div.id = 'test';
div.innerHTML = '<span class="msg">Hello world.</span>';
div.textContent = 'Hello world.';
}
.ui-modal{
width: 200px;
height: 50px;
border: 1px solid red;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="wrapper">
<input type="button" value="ADD" onclick="add_div();">
<input type="button" value="DELETE">
</div>
</body>
</html>
After running this above code And inspecting i am seeing each additionally added div having same ID.
How to generate separate ID?
You can declare a counter outside add_div and append it into id everytime you create a div
var counter = 1;
function add_div(){
var div = document.createElement('div');
document.body.appendChild(div);
div.className = 'ui-modal';
div.id = 'test' + (counter++);
div.innerHTML = '<span class="msg">Hello world.</span>';
div.textContent = 'Hello world.';
}
.ui-modal{
width: 200px;
height: 50px;
border: 1px solid red;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="wrapper">
<input type="button" value="ADD" onclick="add_div();">
<input type="button" value="DELETE">
</div>
</body>
</html>
You can use the length of elements with class img to use that as the suffix to the id:
function add_div(){
var div = document.createElement('div');
document.body.appendChild(div);
div.className = 'ui-modal';
div.id = 'test-' + document.querySelectorAll('.ui-modal > .msg').length;
div.innerHTML = '<span class="msg">Hello world.</span>';
//div.textContent = 'Hello world.';
}
.ui-modal{
width: 200px;
height: 50px;
border: 1px solid red;
}
<div class="wrapper">
<input type="button" value="ADD" onclick="add_div();">
<input type="button" value="DELETE">
</div>

Problem with innerXhtml and onclick attribute

In the XHTML page i have this div:
<div id="listAzioni">
<h4 style="margin-bottom:3px;">List shape :</h4>
</div>
Subsequently incorporated within the div an input element via javascript using the library innerXhtml.
var paper = document.getElementById("listAzioni");
var toWrite = "<h4 style=\"margin-bottom:3px\">List shape :</h4>";
toWrite += "<input type=\"button\" class=\"listButton\" value=\""+id+"\" onclick=\"showAction('"+id+"');\"/>"+'<br/>';
innerXHTML(paper,toWrite);
But after adding the input element has no onclick attribute. I tried so hard but I have not found anything that would solve my problem. Where am I doing wrong?
Which browsers have you tried?
I suggest you to use standard DOM APIs, I write your code as below:
<html>
<head>
<style type="text/css">
.button {
border: 1px solid black;
padding: 3px;
}
</style>
<script type='text/javascript'>
function addButton() {
var container = document.getElementById('container');
if (container != null && container != undefined) {
var child = document.createElement("div");
var button = document.createElement("input");
button.value = "Click to alert";
button.type = "button";
child.style.padding = "10px";
child.style.border = "2px solid red";
button.className = "button";
button.onclick = showAlert;
child.appendChild(button);
container.appendChild(child);
}
}
function showAlert() {
alert("you clicked the button!");
}
</script>
</head>
<body>
<div id="container"></div>
<input value="add div and button" type='button' onclick='addButton();'/>
</body>
</html>

Categories

Resources