<div class="commentArea"></div>
<input class="write" type="text">
<button onclick="summitComment()" class="summit">summit</button>
<script type="text/javascript" src="main.js"></script>
function summitComment() {
let comments = document.getElementsByClassName('commentArea')[0];
let makeDiv = document.createElement('div');
makeDiv.className = 'talking';
comments.appendChild(makeDiv)
let makeUser = document.createElement('span');
let makeMsg = document.createElement('span');
let makeBtn = document.createElement('button');
makeUser.className = "commentUserId";
makeMsg.className = "mentionUserComment";
makeBtn.className = "deleteReply";
makeMsg.innerHTML = reply.value;
makeUser.innerHTML = "User_ID";
makeBtn.innerHTML = "Delete";
for (i=0; 1; i++) {
document.getElementsByClassName('talking')[i].appendChild(makeUser)
document.getElementsByClassName('talking')[i].appendChild(makeMsg)
document.getElementsByClassName('talking')[i].appendChild(makeBtn)
}
}
I'm studying javascript and I try to make comment section for webpage.
first code is HTML code and second is JS code.
but when I write something and click summit button, it's work. but console shows to me error
Uncaught TypeError: Cannot read property 'appendChild' of undefined
I think The tag created by 'createElement' does not seem to be chosen by getElementsByClassName.
I don't know how to solve it.
The reply variable was not defined and this loop on the end I don't think it's needed
function summitComment() {
let comments = document.getElementsByClassName('commentArea')[0];
let reply = document.querySelector('.write');
let makeDiv = document.createElement('div');
makeDiv.className = 'talking';
comments.appendChild(makeDiv);
let makeUser = document.createElement('span');
let makeMsg = document.createElement('span');
let makeBtn = document.createElement('button');
makeUser.className = "commentUserId";
makeMsg.className = "mentionUserComment";
makeBtn.className = "deleteReply";
makeMsg.innerHTML = reply.value;
makeUser.innerHTML = "User_ID";
makeBtn.innerHTML = "Delete";
makeDiv.appendChild(makeUser)
makeDiv.appendChild(makeMsg)
makeDiv.appendChild(makeBtn)
}
<div class="commentArea"></div>
<input class="write" type="text">
<button onclick="summitComment()" class="summit">summit</button>
<script type="text/javascript" src="main.js"></script>
Because appendChild cannot read from undefined
You need check Element exist before append instead of:
var element = document.getElementsByClassName('talking');
for (i=0; 1; i++) {
element?.[i]?.appendChild(makeUser)
element?.[i]?.appendChild(makeMsg)
element?.[i]?.appendChild(makeBtn)
}
Try to use
if (!!comment) comments.appendChild(makeDiv)
instead of only
comments.appendChild(makeDiv)
getElementByClassName returns a single DOM element. You don't need to do '[0]' on it. Remove that and it should work fine.
In case if you use querySelectorAll, then you have get by index since this method returns an array.
Related
Below is my HTML Code, the alert Message returns Undefined i.e the "div_" is not created.
Please help to resolve this:
var piediv = document.createElement('div');
piediv.id = "div_" ;
alert($('#div_').attr('id'));
You need to append the div as body's child first.
var piediv = document.createElement('div');
piediv.id = "div_" ;
document.body.appendChild(piediv);
alert($('#div_').attr('id'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You have to set attribute of div try this 100% worked .
1st Method :
var piediv = document.createElement('div');
piediv.setAttribute("id", "div_");
$("body").append(piediv);
alert($('#div_').attr('id'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2nd Method as suggested by #mplungjan :
var pieDiv = $("<div/>",{"id":"div_"}).appendTo("body");
alert($('#div_').attr('id'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I am trying to achieve a vanilla js alternative for jQuery append(), as I need it to work in Internet Explorer.
I need to replace $('#id2).append(link);
I have tried add innerHTML and insert into a parentNode, however I get the error 'Cannot read property 'insertBefore' of undefined'
let condition = false;
let link = '';
if (condition === true) {
link = `<li class="list>List</li>`;
$('#id1').prepend(link);
}
else {
link = `<a id="button">Button</a>`;
$('#id2').append(link);
}
Markup:
<div id="id1">
<input type="submit" id="id2">
</div>
The above code works fine in all browsers except IE11, which is a requirement. I have tried to replace $('#id2).append(link); with code below, but get error 'insertBefore' of undefined':
const div = document.querySelectorAll('#id2');
const newText = document.createElement('div');
const newText2 = newText.innerHTML = link;
div.parentNode.insertBefore(newText2, div.nextSibling);
Thank you.
You need to be working with DOM elements, not strings. Then, you can append or prepend as shown here:
// Create and configure DOM elements that will be used:
let a = document.createElement("a");
a.id = "button";
a.textContent = "Button";
let li = document.createElement("li");
li.classList.add("list");
li.textContent = "List";
// Get reference to the node to prepend/append to:
let target = document.getElementById("id1");
let answer = +prompt("1 = prepend, 2 = append");
if (answer === 1) {
target.parentNode.insertBefore(a, target);
} else {
target.appendChild(li);
}
<body>
<div id="id1">
<input type="submit" id="id2">
</div>
</body>
I have this part of my html (more than one of same type):
<div class="this-product">
<img src="images/bag2.jpeg" alt="">
<span class="product-name">iPhone</span>
<span class="product-price">345445</span>
</div>
And this part of my javascript code meant to get the innerHTML of the span tags and assign them values as shown:
var productList = document.querySelectorAll('.this-product');
productList.forEach(function (element) {
element.addEventListener('click', function (event) {
var productName = document.getElementsByClassName('product-name')[0].innerHTML;
var productPrice = document.getElementsByClassName('product-price')[0].innerHTML;
var cartProductname = event.currentTarget.productName;
var cartProductprice = event.currentTarget.productPrice;
var cartContent = '<div class="cart-product"><span class="block">'+cartProductname+'</span><span class="block">'+cartProductprice+'</span></div><div class="cart-result">Total = </div><br>'
document.getElementById('dashboard-cart').innerHTML += cartContent;
});
});
Everything works well and every variable above has its value shown well apart from cartProductname and cartProductprice which display as undefined and also vscode tells me that productName is declared but not read. Where could I be wrong?
If I understand your question correctly, you could call querySelector on each product item element that you are iterating like so:
var productList = document.querySelectorAll('.this-product');
productList.forEach(function (element) {
element.addEventListener('click', function (event) {
// Update these two lines like so:
var productName = element.querySelector('.product-name').innerHTML;
var productPrice = element.querySelector('.product-price').innerHTML;
var cartProductname = productName; // event.currentTarget.productName;
var cartProductprice = productPrice; // event.currentTarget.productPrice;
var cartContent = '<div class="cart-product"><span class="block">'+cartProductname+'</span><span class="block">'+cartProductprice+'</span></div><div class="cart-result">Total = </div><br>'
document.getElementById('dashboard-cart').innerHTML += cartContent;
});
});
You can use event.currentTarget.querySelector('.product-name') to get element inside of another element
I'm having some trouble with my code. the only thing i have to make is an add and delete button. The adding part is already done, but the delete part not. it keeps saying:
uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'
Can someone please help me?
Thanks!
Code:
<input type="text" id="txtelement">
<button id="add">result</button>
<button id="delete">Delete latest</button>
<p id="divResult"></p>
<script>
//decline variable
var index = 1;
//adding option
window.onload = function(){
document.getElementById('add').onclick = function(){
var newElement = document.createElement('div');
varElementid = 'div' + index++;
var node = document.getElementById('txtelement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
}
//delete option
document.getElementById('delete').onclick = function(){
var divResult = document.getElementById('divResult');
var alinea = divResult.querySelectorAll('p:last-child')[0];
console.log(alinea + ' word verwijderd...');
divResult.removeChild(alinea);
console.log('verwijderd!');
}
}
:last-child works slightly different than you think it does. p:last-child selects the last child of type p(aragraph) of [whatever parent node you called the method on]'. You don't want to select the p, you want to select the div you just inserted.
var alinea = divResult.querySelectorAll('div:last-child')[0]
Do note that your code doesn't handle the case yet where you delete more elements than you added.
Running code snippet:
//decline variable
var index = 1;
//adding option
window.onload = function() {
document.getElementById('add').onclick = function() {
var newElement = document.createElement('div');
varElementid = 'div' + index++;
var node = document.getElementById('txtelement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
}
//delete option
document.getElementById('delete').onclick = function() {
var divResult = document.getElementById('divResult');
var alinea = divResult.querySelectorAll('div:last-child')[0];
console.log(alinea + ' word verwijderd...');
divResult.removeChild(alinea);
console.log('verwijderd!');
}
}
<input type="text" id="txtelement">
<button id="add">result</button>
<button id="delete">Delete latest</button>
<p id="divResult"></p>
Here is my code for my current todo list.
<html>
<head>
<title>ToDo</title>
</head>
<body>
<script>
function addText(){
var input = document.getElementById('input').value;
var node = document.createElement("P");
var textnode = document.createTextNode(input);
node.appendChild(textnode);
document.getElementById('do').appendChild(node);
}
</script>
<p id="do"> </p>
<input type='text' id='input'/>
<input type='button' onclick='addText()' value='Add To List'/>
</body>
</html>
It works to add objects but I have no idea what the javascript is to remove objects?
I wonder if someone could help me with a remove script like a X mark on the side of a new added object or something just to remove 1 after you add it,
Cheers
I think I found a solution to your problem. Check my fiddle:
http://jsfiddle.net/Kq4NF/
var c = 1;
function addText(){
var input = document.getElementById('input').value;
var node = document.createElement("P");
node.setAttribute('id', 'anchor'+c);
var textnode = document.createTextNode(input);
node.appendChild(textnode);
var removenode = document.createElement("input");
removenode.setAttribute('type', 'button');
removenode.setAttribute('value', 'X');
removenode.setAttribute("onclick", "removeText('anchor"+c+"')");
node.appendChild(removenode);
c++;
document.getElementById('do').appendChild(node);
}
function removeText(item){
var child=document.getElementById(item);
document.getElementById('do').removeChild(child);
}
Good luck!
var list = document.getElementById("do");
list.removeChild(list.childNodes[0]);
list - represents the p tag with ID do
list.ChildNodes - list of child elements appended to your p tag with ID as do.
list.ChildNodes[0] - represents the first child appended to the list, where 0 is the index.
To remove a specific element, either represent the is as index or point directly the element like
var list = document.getElementById("do");
var node = document.createElement("P");
var textnode = document.createTextNode(input);
textnode.id = "do1"; // Add id to the child element
node.appendChild(textnode);
document.getElementById('do').appendChild(node);
// This is to remove it using ID
list.removeChild(document.getElementById("do1"));
Hope you can understand.