简体   繁体   English

如何用div包装除第一个元素之外的所有元素

[英]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我需要包装所有元素,但第一个在单独的 div 中,以便我可以用 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:到目前为止,我已经成功地在文章的开头插入了一个包装 div:

  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!提前致谢!

 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>

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM