I have this function code that I am using to create a code snippet in javascript. I want to know if I can make it look better since I think this code I did is not looking professionally well.
I tried using destructuring but for some reason, my browser show me this message Uncaught TypeError: Cannot read property 'appendChild' of undefined
I would like to know if there is any better way of passing multiple parameters to a function in javascript sending the arguments as an object literal? And Why does it say that the string contains an invalid character?
Many thanks.
const create = function ({t, v, p}) { let n = document.createElement(t); n.innerHTML = v; p.appendChild(n); return n; }; // create the list for reference let ul = create({ t: 'ul', v: null, p: document.body });
Here is the full JS code.
const createsnippets = function (e) { // the reference node -- we atually have one ID for headlines let headlines = document.getElementById('headlines'); // utility function to add new HTML DOM element const create = function ({t, v, p}) { let n = document.createElement(t); n.innerHTML = v; p.appendChild(n); return n; }; // create the list for reference let ul = create({ t: 'ul', v: null, p: document.body }); // find all newsarticle classess and add then to snippet in sequence Array.from(document.querySelectorAll('article.newsarticle > h4')).forEach(function (h4) { create('li', h4.textContent + '... ' + h4.nextElementSibling.innerText, ul); }); // insertion re-factors HTMl to ensure the layout (markup and CSS) when displaed headlines.parentNode.insertBefore(ul, headlines.nextSibling) } // once prepared, we can display the loaded content as snippet/collection document.addEventListener('DOMContentLoaded', createsnippets);
Your parameter destructuring is fine, but you're calling create
in two different ways. This call is fine:
let ul = create({
t: 'ul',
v: null,
p: document.body
});
...but this one is not:
create('li', h4.textContent + ' ... ' + h4.nextElementSibling.innerText, ul);
This will cause your create function to try to destructure a t
, v
, and p
property from the string 'li'
. The destructuring code translates roughly to this, and here's what would happen with that second call:
function(param) { // param = 'li'
let t = param.t; // t = 'li'.t -> t = undefined
let v = param.v; // v = 'li'.v -> v = undefined
let p = param.p; // p = 'li'.p -> p = undefined
let n = document.createElement(t); // n = document.createElement(undefined)
n.innerHTML = v;
p.appendChild(n); // undefined.appendChild(n)
return n;
}
Perhaps you meant to do:
create({
t: 'li',
v: `${h4.textContent} ... ${h4.nextElementSibling.innerText}`,
p: ul
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.