+ 1
Why is my childNode returning undefined?
I'm trying to split the first p tag into 3 separate lines by using javascript. but I'm getting a return value of undefined. Can someone pls help me? https://code.sololearn.com/WA14a102a7a7
1 Resposta
+ 1
You're running into the problem because a span element doesn't have a childNode property. It has childNodes( notice the s at the end there ), firstChild, lastChild but not childNode. innerHTML can do what you want with less code, though.
I'm not sure why but I also ran into a "breakLineFunction already declared" JavaScript error while running your code on Sololearn Playground also. This message disappeared when I moved your breakLineFunction definition into your DOMContentLoaded callback.
Your for-loop also iterated i over the 0, 1... like you probably want but then it iterated over 'entries', 'keys', 'values', 'forEach', 'length', 'item' which you probably don't want. For this reason, I would use the forEach method like below.
This works like you describe:
document.addEventListener("DOMContentLoaded", () => {
const breakLineFunction = () => {
const spans = document.querySelectorAll("span");
let newLine = "";
spans.forEach((span) => {
newLine += span.innerHTML + "<br><br>";
});
document.querySelector(".lineBreak").innerHTML = newLine;
}
document.querySelector("#fixLineBreak").addEventListener("click", breakLineFunction);
})