How can I append the word variable to my div? - javascript

I guess it will not let me because it is returning a string. The error I get is "Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'". How can I write this piece of code correctly?
getWord() {
let words = ["Movies", "Series", "DC Comics", "Batman"];
let word = words[Math.floor(Math.random() * words.length)];
let div = document.createElement("div");
div.appendChild(word);
}

Try div.innerText = word. Because you are trying to insert a String as a node.

If you want to stick with the div.appendChild() so that you could change the styling or element tag name of the text node in the future, you could create a text node and append it to the div instead, like so:
var text = document.createTextNode(word);
div.appendChild(text);

in your example you trying append string in the element, it's not correct, an argument for appendChild method should be element, for example:
const parent = document.createElement("div");
parent.appendChild(document.createElement("div"));
For your case, when you need to add content to the element, you should use textNode:
const title = document.createElement("H1");
const text = document.createTextNode("Movies");
title.appendChild(text);
Or:
const title = document.createElement("H1");
title.textContent = "Series";

Related

cant append text node to element using javascript

im trying to get some data from another html page and create an element in javascript and then added it to the dom
so far im trying to append a text node inside an h1 and p element from a variable
the console shows this error
script.js:32 Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
at script.js:32:7
this is the code i will add some comments to clarify :
window.addEventListener("load",() =>{
const data = (new URL (document.location)).searchParams;
// all of these are strings
const title = data.get('title');
const desc = data.get('desc');
const date = data.get("date");
const PDF = data.get("pdf");
// elmenet creation
const columns = document.createElement("div");
const worksheetCon=document.createElement("div");
const card = document.createElement("div");
const imageDiv = document.createElement("div");
const image = document.createElement("img");
const h1 = document.createElement("h1");
// creating h1 elment text node to append it later to h1 element
const h1Text = document.createTextNode(title);
const contain = document.createElement("div");
const p =document.createElement("p");
// creating p elment text node to append it later to append it later to p element
const Ptext = document.createTextNode(desc);
// trying to figure out type of text node it says its object
alert(typeof Ptext);
worksheetCon.className = "container-worksheets";
columns.className = "columns";
card.className = "carde";
imageDiv.className = "img";
contain.className = "contain";
worksheetCon.appendChild(columns);
columns.appendChild(card);
card.appendChild(imageDiv);
imageDiv.appendChild(image);
card.appendChild(h1);
h1.appendChild(h1Text)
card.appendChild(contain);
contain.appendChild(p);
p.appendChild(Ptext );
const worksheets = document.querySelector("worksheets");
worksheets.appendChild(card);
})
As I said, you never use Ptext, but you try to use desc as a Node
const desc = data.get('desc');
p.appendChild(desc);

Wrapping a string in a div in pure javascript

Is there a way in pure javascript to wrap a nacked string?
I have a string that I'm splitting based on a character to separate the header from the rest of the content. I would very much like to style that header, but i can't seem to find a good way to wrap a div around it with a class.
All I can seem to find is wrapping a div around something that already has other elements.
My code looks like this
var string = "Title*This is the very long content";
var title = string.split('*')[0]
var body = string.split('*')[1]
//put them back together
string = title + body;
but i can't seem to find a good way to wrap a div around it with a
class?
You can create an element (which is at the end a tag HTML) with createElement
and attach it a class with className
let string = "Title*This is the very long content";
/*
let title = string.split('*')[0]
let body = string.split('*')[1]
*/
let [title, body] = string.split('*'); // Destructuring assignment
let headerTitle = document.createElement('h1');
headerTitle.textContent = title;
headerTitle.className = "red";//headerTitle.classList.add('red');
let bodyHTML = document.createElement('p');
bodyHTML.textContent = body;
document.querySelector('#content').innerHTML = headerTitle.innerHTML +"<br/>"+ bodyHTML.innerHTML;
.red{
color: red;
}
<div id="content" />
Tip Try to avoid var keyword for declaring variable and replace them with either let or const and better using Destructuring assignment

Problems when parsing nested html tags from string

I have this code that's to parse a string into html and display the text of each element.
That's working good except when I have nested tags for example <div><p>Element 1</p><p>Element 2</p></div>. In this case, the code displays <p>Element 1</p><p>Element 2</p>.
How can I do to get each tags one after the other ? (Here I want Element 1 and then Element 2)
Here's the code :
let text = new DOMParser().parseFromString(stringHtml, 'text/html');
let textBody = text.body.firstChild;
while (textBody) {
alert(textBody.innerHTML);
// other actions on the textBody element
textBody = textBody.nextSibling;
}
Thanks for helping me out
It sounds like you want a recursive function that prints the textContent of itself, or of its children, if it has children:
const stringHtml = '<div><p>Element 1</p><p>Element 2</p></div><div><p>Element 3</p><p>Element 4</p></div>';
const doc = new DOMParser().parseFromString(stringHtml, 'text/html');
const showElms = parent => {
const { children } = parent;
if (children.length) Array.prototype.forEach.call(children, showElms);
else console.log(parent.textContent);
}
showElms(doc.body);
That's assuming you want to iterate over the actual elements. If you want all text nodes instead, then recursively iterate over the childNodes instead.

How can I get the raw value of a text node?

Let's say I have the following:
var div = document.createElement('div');
div.innerHTML = "<";
var nodes = div.childNodes;
console.log(nodes)
then in all fields of nodes[0] (i.e. nodes[0].data, nodes[0].nodeValue, nodes[0].textContent, nodes[0].wholeText) I get <. Can I retrieve the "raw" value of a text node somehow? In this case <. Or is the only option to first retrieve it parsed, and then to escape the html somewhat like this:
function escapeHtml(html) {
var text = document.createTextNode(html);
var div = document.createElement('div');
div.appendChild(text);
return div.innerHTML;
}
Note: I consciously chose childNodes in order to get text-nodes as well as non-text-nodes.

Why can't I append to a <p> tag?

I am working on the scripting a ToDo list webapp, and I am trying to take the contents of 4 text boxes to create the content of the ToDo item.
Currently, when I try to connect the elements generated from the form, I get the error TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
at HTMLButtonElement.document.getElementsByClassName.onclick
I am currently using a function to create the element that I want to append to the body of the ToDo item, and I believe I am returning an element from my function. The code is posted below.
document.getElementsByClassName('modal-accept-button')[0].onclick = function () {
var formVals = {
what: document.getElementById('todo-input-what').value,
where: document.getElementById('todo-input-where').value,
when: document.getElementById('todo-input-when').value,
who: document.getElementById('todo-input-who').value,
details: document.getElementById('todo-input-details').value
};
document.getElementsByTagName('main')[0].appendChild(function () {
var fields = ["where", "when", "who", "details"];
var root = document.createElement("SECTION").className = "todo";
var title = document.createElement("H2").value = formVals.what;
var body = document.createElement("DIV").className = "todo-body"
for (var i = 0; i < fields.length; i++) {
var currentField = fields[i];
var currentVal = formVals.currentField;
body.appendChild(function () {
var p = document.createElement("P").className = "indent-wrapped";
var span = document.createElement("SPAN").class = currentField;
var text = document.createTextNode(currentVal);
span.value = currentField + ": ";
p.appendChild(span);
p.appendChild(text);
return p;
});
}
root.appendChild(title);
root.appendChild(body);
return root;
});
resetModal();
}
The variable p is not an item (HTML "Node"); it is a string.
That is, because you assigned it a string, using a sequence assignment (the last value goes all the way back) - "indent-wrapped" goes into className and then className goes into p.
Separate the item creation from the class assignment:
var p = document.createElement("P")
p.className = "indent-wrapped"
Same goes for root, title and span. They all are being assigned strings the same way.
You assign the string indent-wrapped to p, as you can see in the following snippet. So you try to call appendChild on a string instead of a node. Split the assignment, so you will first assign the node to p, and in the next statement set its classname. The same goes for the other elements (root, title, body, etc) where you try to create the element and set one of their properties in the same statement.
var p = document.createElement("P").className = "indent-wrapped";
console.log(p);

Categories

Resources