I am relatively new to using map() in JavaScript so I'm still in the process of learning the ropes behind it. I am struggling to pull together all of my items in my list that only include a specific word, at the minute It's only pulling through the first item in the list. Can anyone please explain to me where I've gone wrong with this and what I need to do to fix this issue?
Here is my code below for reference - Any help with this issue would be seriously appreciated.
<div >
<li>Model UK 8</li>
<li>Model Height 5 ft 8</li>
<li>Colour: Blue</li>
</div>
const addElement = function(){
const targetLI = [...document.querySelectorAll('.target-description li')];
targetLI.map((item) => {
if (item.innerText.includes('Model')) {
item.style.display = 'none';
const modelwear = document.createElement("div");
const model = {};
let desc = item.innerText;
model.desc = desc;
modelwear.id = "model";
modelwear.innerHTML = `<div >
<span >Model Information:</span>
<div >
<div >
</div>
<div >
<span >${model.desc}</span>,<br>
</div>
</div>
</div>
</div>`;
const homepageTarget = document.querySelector('.target-description');
if (document.getElementById('model') === null) {
const parent = homepageTarget.parentNode;
parent.insertBefore(modelwear, homepageTarget);
} else {
document.querySelectorAll('.model-desc').innerText = desc;
}
} else if (!item.innerText.includes('Model')) {
item.style.display = "list-item";
}
});
};
addElement();
CodePudding user response:
The .map()
method simply maps out a new array based on the items in the source array. For your case, it looks like you need the forEach()
method.
targetLI.forEach((item) => { //...
Hope this helps.
CodePudding user response:
I have noticed that you doing right but you are miss typed
parent.insertBefore(modelwear, homepageTarget); calling only ones I have attached the code below you can take a look. `
const addElement = function(){
const targetLI = [...document.querySelectorAll('.target-description li')];
targetLI.map((item,i) => {
if (item.innerText.includes('Model')) {
item.style.display = 'none';
const modelwear = document.createElement("div");
const model = {};
let desc = item.innerText;
model.desc = desc;
modelwear.id = "model";
modelwear.innerHTML = `
<div >
<span >Model Information:</span>
<div >
<div >
</div>
<div >
<span >${model.desc}</span>,<br>
</div>
</div>
</div>
</div>`;
const homepageTarget = document.querySelector('.target-description');
const parent = homepageTarget.parentNode;
if (document.getElementById('model') === null) { // in the first iteration null but int secod iteration its not null
parent.insertBefore(modelwear, homepageTarget); // so you need pass this for
} else {
document.querySelectorAll('.model-desc').innerText = desc;
parent.insertBefore(modelwear, homepageTarget); //here too
}
} else if (!item.innerText.includes('Model')) {
item.style.display = "list-item";
}
});};addElement();