3

Just staring to lean js here. Is it possible to move child elements from one parent under another parent if parent name is duplicate?

Example:

How to put Something else & Something like under a single Composition parent, and Someone else under one Content, and delete the duplicates. Is this possible with javascript or jquery? Thank you!

<li>
  <h4>Composition</h4>
  <p>Something</p>
</li>
<li>
  <h4>Composition</h4>
  <p>Something else</p>
</li>
<li>
  <h4>Composition</h4>
  <p>Something like</p>
</li>

<li>
  <h4>Content</h4>
  <p>Someone</p>
</li>
  <h4>Content</h4>
  <p>Someone else</p>
</li>

here is the js I got so far, I'm stuck at moving p items to the first element that repeats, each under it's parent. thing is parent elements don't have certain id's or classes:

const $technicalProp = $("[data-surface-prop]");
const technicalVal = $("[data-surface-val]");
let duplicate = {};

$technicalProp.each(function() {
  let txt = $(this).text();

  if (duplicate[txt]) {
     $(this).remove(); // this only removes the dulicate names I also need to move chlidren
  }
  else {
    duplicate[txt] = true;
  }
});
Alina
  • 45
  • 4

2 Answers2

1

yes you can i dont know if this is the best way but this works, my approach is by making an arrayobject (js) as a new model of what you want

the logic is i extract the text of h4 and check if the data variable has been registered there, if not registered yet then i push it to the data and the child text (p) if registered already then i push the child text only

let data = [];
        const lists = document.querySelectorAll('li').forEach( (li, liIdx) => {
            let parentName = li.querySelector('h4').innerHTML;
            let childName = li.querySelector('p').innerHTML;
            let isRegistered = data.find( x => x.parentName === parentName);
            if(!isRegistered) {
                childName = [childName];
                data.push({ parentName, childName});
            }else {
                console.log(isRegistered)
                isRegistered.childName.push(childName);
            }
        });

and this is what we got

0:
childName: (3) ["Something", "Something else", "Something like"]
parentName: "Composition"
1:
childName: (2) ["Someone", "Someone else"]
parentName: "Content"

then reset the ol tag and rebuild its item

let ol = document.querySelector('ol');
ol.innerHTML = '';

        data.map( d => {
            let p = d.childName.map( c => `<p>${c}</p>`).join('');
            ol.insertAdjacentHTML('beforeend', `
                <li>
                    <h4>${d.parentName}</h4>
                    ${p}
                </li>
            `);
        })
-1

With jQuery you can remove and add elements with detach(), append() and prepend()

Like here: https://stackoverflow.com/a/19802593/11265780 (but replace jQuery with $)