I am completely new to Javascript (and Stack Overflow) and I want to build a blog that allows the user to create a div onclick. I referenced this article on w3shool and tried all the three methods listed. However, the div doesn't show up when I use the first two methods and appears without clicking when I use the third one.
Here's my code for the third method:
HTML
<button class="box4" id="newEntry">NEW</button>
Javascript
const parent = document.getElementById("entries");
document.getElementById("newEntry").addEventListener("click", newEntry);
function newEntry() {
var newDiv = document.createElement("div");
parent.appendChild(newDiv);
}
For the second method, I replaced line 2 with
document.getElementById("newEntry").onclick= function () {newEntry()};
I have seen similar questions, but none of them solved my problem, so I would really appreciate your help.
There's nothing wrong with you code. It works fine. just one thing you have to remember: Div by default have no height, so if you want make sure to visualize it, just add height and color to it, like the code bellow.
const parent = document.getElementById("entries");
parent.style.width = '150px';
parent.style.height = '150px';
parent.style.backgroundColor = 'red';
document.getElementById("newEntry").addEventListener("click", newEntry);
function newEntry() {
var newDiv = document.createElement("div");
newDiv.style.width = '50px';
newDiv.style.height = '50px';
newDiv.textContent = 'Entry';
newDiv.style.backgroundColor = 'white';
parent.appendChild(newDiv);
}
<div id="entries"></div>
<button id="newEntry">new Entry</button>
Here is an example:
You can use querySelectorAll with a css selector to query all the elements matching the selector, but you can use the getElementByName too. In your example you query the elements by ID, but I don't se where you set the ids.
function onInitClick(){
const buttons = document.querySelectorAll('button');
const secondButton = buttons[1];
secondButton.addEventListener('click', createButtonAndAppend);
secondButton.innerText = 'Click me';
}
function createButtonAndAppend(){
const button = document.createElement('button');
button.addEventListener('click', createButtonAndAppend);
button.innerText = 'Adds another button';
document.body.append(button);
}
<button onclick="onInitClick();">Add click to second button</button> <button>Nothing happens</button>
you can do it simply using jquery.
if you want to add something to div,
$("#your_div_id").html("your child element")
for example
<div id="example"></div>
$("#example").html("<h1>Hello world</h1>")
then result is
<div id="example"><h1>Hello world</h1></div>