I am working on a cards project and I am having a problem I wrote a function and use the creatTextNode then I append into a variable with append child but that didn't work !! it gave me
( Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. ) on Edge
and
( Uncaught TypeError: Node.appendChild: Argument 1 is not an object. ) on firefox.
let container = document.createElement('div');
document.body.appendChild(container);
container.style.textAlign = 'center';
function project() {
let card = document.createElement('div');
let title = document.createElement('h2');
let age = document.createElement('p');
let img = document.createElement('img');
// add content
let head = document.createTextNode('name');
let ageContent = document.createTextNode('ages');
img.src = "warrior-bear-fantasy-portrait-illustration_691560-268.webp";
title.appendChild('head'); // PROPLEM HERE !
age.appendChild('ageContent'); // AND HERE !
// place the element
card.appendChild('title');
card.appendChild('age');
card.appendChild('img');
container.appendChild('card');
}
console.log(project())
Related
I have an array of objects that I want to display in a template. I wrote the function below and its almost working except when I click on an li, the properties of the object remain the same and don't change if I click on a different li; this is the error that I get : // uncaught TypeError: Cannot read properties of null (reading 'content') at HTMLUListElement.
Here is the code I am using :
function afficherDetailsPokemon() {
const listPokemons = document.getElementById('list-pokemons');
listPokemons.addEventListener('click', event => {
if (event.target.tagName === 'LI') {
const pokemonId = event.target.dataset.pokemonId;
const pokemon = pokemons.find(p => p.id === Number(pokemonId));
if (pokemon) {
// Clone the template
const template = document.getElementById('template').content.cloneNode(true);
// Set the values of the form elements to the properties of the Pokemon object
template.querySelector('#nom_en').value = pokemon.name.english;
template.querySelector('#nom_fr').value = pokemon.name.french;
template.querySelector('#attaque').value = pokemon.base.Attack;
template.querySelector('#defense').value = pokemon.base.Defense;
// Create a new span element for each type and append it to the type_p element
pokemon.type.forEach(type => {
const span = document.createElement('span');
span.textContent = type;
template.querySelector('#type_p').appendChild(span);
});
// Replace the info div with the template
const infoDiv = document.getElementById('info');
infoDiv.parentNode.replaceChild(template, infoDiv);
}
}
});
}
I am pretty new to js and would appreciate your help.
When I click on an li, it does display the properties of the name I select first, but when I try a second time I get the error // uncaught TypeError: Cannot read properties of null (reading 'content') at HTMLUListElement.
If it helps, this happens on the line where I clone the template.
I have a list of driver names, that is displayed on my page and I want to get more information about the driver when I click on the name. I am struggling with running a function.
Here's what my html looks like:
<main>
<nav id="list">
</nav>
<section id="profile">
</section>
That's my list:
const drivers = [{
name: "data",
age: "data1",
nationality: "data2"
}]
And that's the function I am trying to run:
function driverProfile(drivers) {
const article = document.createElement('article');
const span = document.createElement('span');
const h2 = document.createElement('h2');
h2.textContent = drivers[driver_id].nationality;
span.textContent = drivers[driver_id].age;
article.textContent = drivers[driver_id].name;
}
myProfile = driverProfile(drivers)
profile.appendChild(myProfile)
I get this error Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. pointing to profile.appendChild(myProfile)
My list function:
drivers.forEach(addLink);
function addLink(driver, index) {
const a = document.createElement('a');
a.href = `?driver=${index}`;
a.textContent = driver.name;
list.appendChild(a);
}
It is better practice to group elements. First append elements in div then append new divs to section:
function driverProfile(drivers) {
const div = document.createElement("div");
const article = document.createElement('article');
const span = document.createElement('span');
const h2 = document.createElement('h2');
h2.textContent = drivers[driver_id].nationality;
span.textContent = drivers[driver_id].age;
article.textContent = drivers[driver_id].name;
div.appendChild(h2);
div.appendChild(span);
div.appendChild(article);
return div;
}
myProfile = driverProfile(drivers);
profile.appendChild(myProfile);
The program give error because your function is not of return type and you are assigning function to myProfile variable.
appendChild function takes html elements as Object but you had given function. Just change function to return type as shown in above code.
driverProfile is not returning any node. At the end of this function you need to return the node you want to be appended.
I am getting the error:
div.setAttribute is not a function
in the following code snippet:
FriendlyChat.prototype.displayMessage = function(key, name, text, picUrl, imageUri) {
console.log('FriendlyChat.prototype.displayMessage');
var div = document.getElementById(key);
// If an element for that message does not exists yet we create it.
if (!div) {
var container = document.createElement('div');
container.innerHTML = FriendlyChat.MESSAGE_TEMPLATE;
div = container.firstChild;
div.setAttribute('id', key);
this.messageList.appendChild(div);
}
if (picUrl) {
div.querySelector('.pic').style.backgroundImage = 'url(' + picUrl + ')';
}
div.querySelector('.name').textContent = name;
var messageElement = div.querySelector('.message');
if (text) { // If the message is text.
messageElement.textContent = text;
// Replace all line breaks by <br>.
messageElement.innerHTML = messageElement.innerHTML.replace(/\n/g, '<br>');
}
};
The error occurs whenever the above function is called. I don't know what is wrong with the code.
Why does the error occur?
container.firstChild returns the first child node within container, which may not be an element (it could be a text node, comment, etc.). If it's not an element, it won't have setAttribute. If you want the first element child, use firstElementChild.
Side note: id is a reflected property, so you can write div.id = key; rather than div.setAttribute("id", key);. They do the same thing. (This is true of many attributes, but not all; value on input elements is a major exception, it's not an accessor for the value attribute.)
I'm trying to dynamically generate chat but the messages get inserted below the previous meaning the user has to scroll down to see a new message which isn't very good! I'm trying to change it so the message gets inserted above the last message.
var elementDiv = document.createElement("div");
elementDiv.className = "chat-message error";
elementDiv.appendChild(document.createTextNode(chatBoxMessage));
//Insert message
var oldMsg = "chat-message";
document.getElementsByClassName('message-window').appendChild(elementDiv);
document.body.insertBefore(elementDiv, oldMsg);
The variable chatBoxMessage is used to define the text.
Running this throws the error -
Uncaught TypeError: Failed to execute 'insertBefore' on 'Node' : parameter 2 is not of type 'Node'.
Seems like oldMsg is a string type. You'll have to call document.createTextNode with the oldMsg in order for it to work.
I made a sample implementation. Hopefully this is what you are looking for:
HTML:
<div id='container'></div>
Javascript:
// select the container
var container = document.getElementById('container');
// create chat messages
var msg1 = createChatMsg('Chat1');
var msg2 = createChatMsg('Chat2');
var msg3 = createChatMsg('Chat3');
// Insert Messages
container.insertBefore(msg1, container.firstChild);
container.insertBefore(msg2, container.firstChild);
container.insertBefore(msg3, container.firstChild);
// create chatmessage
function createChatMsg(message) {
var chatMsg = document.createElement('div');
chatMsg.className = 'some-chat';
chatMsg.appendChild(document.createTextNode(message));
return chatMsg;
}
Hopefully this helps and is what you are looking for. Sample implementation: http://jsfiddle.net/f1d02e49/
You may need to wrap your message in a text node.
document.createTextNode("chat-message");
Your error message indicates that your text is not a valid node.
parameter 2 is not of type 'Node'
See: MDN - Document.createTextNode()
onReady('#message-window', function() {
pushNewMessage('Third!');
pushNewMessage('Second!');
pushNewMessage('First!');
});
function pushNewMessage(chatBoxMessage) {
var errorMessageDiv = document.createElement('div');
errorMessageDiv.className = 'chat-message error';
errorMessageDiv.appendChild(document.createTextNode(chatBoxMessage));
//Insert message
var messageWindow = document.getElementById('message-window');
messageWindow.insertBefore(errorMessageDiv, messageWindow.firstChild);
}
// Convinience function -- Wait for element or body load...
function onReady(selector, callback, ms) {
var intervalID = window.setInterval(function() {
if ((document.querySelector(selector) || document.body) !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}, ms || 500);
}
<div id="message-window">
</div>
I have a code that is working fine in ie8 but in ie11 it's giving me error -"unable to get property 'value' of undefined or null reference "while debugging. I am adding just a part of function. If you notice it is working fine for other elements just on isSpanish it is failing. Any suggestions are welcome.
function callSchedule() {
document.getElementById("hideCallbackRow").style.display = "block";
document.getElementById("scheduleCallBtn").disabled = true;
var callbackDate = '';
var callbackCallTimeZone = '';
var callbackCallTime = '';
var spanish = '';
if(document.getElementById("fromDate1") && document.getElementById("requestedCallTimeZoneSelectedVal") && document.getElementById("requestedCallTimeSelectedVal")){
setCallbackValues();
callbackDate = document.getElementById("fromDate1").value;
callbackCallTimeZone = document.getElementById ("requestedCallTimeZoneSelectedVal").value;
callbackCallTime = document.getElementById("requestedCallTimeSelectedVal").value;
spanish = document.getElementById("isSpanish").value;