JakePowell
JakePowell

Reputation: 100

How to wrap all but first element with div

I need to wrap all elements but the first in a separate div so I can display them with flex

so this:

<article>
    <div>image</div>
    <div>title</div>
    <div>byline</div>
    <div>read-more</div>
</article>

to this:

<article>
    <div>image</div>
    <div>
        <div>title</div>
        <div>byline</div>
        <div>read-more</div>
    </div>
</article>

So far I've managed to insert a wrapper div at the start of the article with this:

  const postImage = document.querySelector('.w-blog-grid > a > article > div');
  const wrapper = document.createElement('div');
  postImage.parentNode.insertBefore(wrapper, postImage);
  

Any ideas? Thanks in advance!

Upvotes: 0

Views: 249

Answers (2)

The Bomb Squad
The Bomb Squad

Reputation: 4337

function putInLine(element,numChildrenToSkip){
  if(!numChildrenToSkip){numChildrenToSkip=0}
  //numChildrenToSkip is the number of divs you DON'T want inline
  var el=element.childNodes
  var article=Object.keys(el)
  .filter(a=>el[a].tagName=='DIV').map(a=>el[a])
  //article is an array of divs in element
  article.splice(0,numChildrenToSkip)
  var newDiv=document.createElement('div')
  article.forEach(a=>{
    element.removeChild(a)
    newDiv.appendChild(a)
  })
  //article was used to place desired elements in a div of its own
  element.appendChild(newDiv)
  //newDiv nested in element
}

//implementation of function below
putInLine(document.getElementById('article'),1)

//proof that it works
console.log(document.getElementById('article').children)
<article id="article">
    <div>image</div>
    <div>title</div>
    <div>byline</div>
    <div>read-more</div>
</article>

Upvotes: 1

Refat Alsakka
Refat Alsakka

Reputation: 561

const article = document.querySelectorAll('article')[0];
const divs = [...article.querySelectorAll('> div')];
const postImage = divs.shift();
const wrapper = document.createElement('div');

article.innerHTML = '';
divs.forEach(div => wrapper.appendChild(div));
article.appendChild(postImage);
article.appendChild(wrapper);

Upvotes: 0

Related Questions