将内容包装在 div 中的纯 javascript 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6838104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:23:55  来源:igfitidea点击:

Pure javascript method to wrap content in a div

javascripthtmlword-wrap

提问by Squadrons

I want to wrap all the nodes within the #slidesContainerdiv with JavaScript. I know it is easily done in jQuery, but I am interested in knowing how to do it with pure JS.

我想#slidesContainer用 JavaScript包装div 中的所有节点。我知道这在 jQuery 中很容易完成,但我有兴趣知道如何使用纯 JS 来完成。

Here is the code:

这是代码:

<div id="slidesContainer">
    <div class="slide">slide 1</div>
    <div class="slide">slide 2</div>
    <div class="slide">slide 3</div>
    <div class="slide">slide 4</div>
</div>

I want to wrap the divs with a class of "slide" collectively within another div with id="slideInner".

我想用id="slideInner".

回答by Michal

If your "slide"s are always in slidesContainer you could do this

如果您的“幻灯片”始终在 slidesContainer 中,您可以这样做

org_html = document.getElementById("slidesContainer").innerHTML;
new_html = "<div id='slidesInner'>" + org_html + "</div>";
document.getElementById("slidesContainer").innerHTML = new_html;

回答by user1767210

Like BosWorth99, I also like to manipulate the dom elements directly, this helps maintain all of the node's attributes. However, I wanted to maintain the position of the element in the dom and not just append the end incase there were siblings. Here is what I did.

和 BosWorth99 一样,我也喜欢直接操作 dom 元素,这有助于维护节点的所有属性。但是,我想保持元素在 dom 中的位置,而不仅仅是在有兄弟姐妹的情况下追加结尾。这是我所做的。

var wrap = function (toWrap, wrapper) {
    wrapper = wrapper || document.createElement('div');
    toWrap.parentNode.appendChild(wrapper);
    return wrapper.appendChild(toWrap);
};

回答by aroth

If you patch up document.getElementsByClassName for IE, you can do something like:

如果您为 IE 修补 document.getElementsByClassName,您可以执行以下操作:

var addedToDocument = false;
var wrapper = document.createElement("div");
wrapper.id = "slideInner";
var nodesToWrap = document.getElementsByClassName("slide");
for (var index = 0; index < nodesToWrap.length; index++) {
    var node = nodesToWrap[index];
    if (! addedToDocument) {
        node.parentNode.insertBefore(wrapper, node);
        addedToDocument = true;
    }
    node.parentNode.removeChild(node);
    wrapper.appendChild(node);
}

Example: http://jsfiddle.net/GkEVm/2/

示例:http: //jsfiddle.net/GkEVm/2/

回答by Bosworth99

I like to manipulate dom elements directly - createElement, appendChild, removeChild etc. as opposed to the injection of strings as element.innerHTML. That strategy does work, but I think the native browser methods are more direct. Additionally, they returns a new node's value, saving you from another unnecessary getElementByIdcall.

我喜欢直接操作 dom 元素 - createElement、appendChild、removeChild 等,而不是像element.innerHTML. 该策略确实有效,但我认为本机浏览器方法更直接。此外,它们会返回一个新节点的值,从而避免另一个不必要的getElementById调用。

This is really simple, and would need to be attached to some type of event to make any use of.

这真的很简单,需要附加到某种类型的事件才能使用。

wrap();
function wrap() {
    var newDiv = document.createElement('div');
    newDiv.setAttribute("id", "slideInner");
    document.getElementById('wrapper').appendChild(newDiv);
    newDiv.appendChild(document.getElementById('slides'));
}

jsFiddle

js小提琴

Maybe that helps your understanding of this issue with vanilla js.

也许这有助于您理解 vanilla js 的这个问题。

回答by Ansikt

A general good tip for trying to do something you'd normally do with jQuery, without jQuery, is to look at the jQuery source. What do they do? Well, they grab all the children, append them to a a new node, then append that node inside the parent.

尝试做一些你通常用 jQuery 做的事情的一般好技巧,没有 jQuery,是查看 jQuery 源代码。他们在做什么?好吧,他们获取所有子节点,将它们附加到一个新节点,然后将该节点附加到父节点中。

Here's a simple little method to do precisely that:

这是一个简单的小方法来做到这一点:

const wrapAll = (target, wrapper = document.createElement('div')) => {
  ;[ ...target.childNodes ].forEach(child => wrapper.appendChild(child))
  target.appendChild(wrapper)
  return wrapper
}

And here's how you use it:

以下是您如何使用它:

// wraps everything in a div named 'wrapper'
const wrapper = wrapAll(document.body) 

// wraps all the children of #some-list in a new ul tag
const newList = wrapAll(document.getElementById('some-list'), document.createElement('ul'))

回答by BG Bruno

I think here is very good code example - this solution preserves binded events

我认为这是非常好的代码示例 - 此解决方案保留绑定事件

// element that will be wrapped
var el = document.querySelector('div.wrap_me');
// create wrapper container
var wrapper = document.createElement('div');
// insert wrapper before el in the DOM tree
el.parentNode.insertBefore(wrapper, el);
// move el into wrapper
wrapper.appendChild(el);

or

或者

function wrap(el, wrapper) {
    el.parentNode.insertBefore(wrapper, el);
    wrapper.appendChild(el);
}
// example: wrapping an anchor with class "wrap_me" into a new div element
wrap(document.querySelector('a.wrap_me'), document.createElement('div'));

ref

参考

https://plainjs.com/javascript/manipulation/wrap-an-html-structure-around-an-element-28/

https://plainjs.com/javascript/manipulation/wrap-an-html-structure-around-an-element-28/

回答by Ershad Qaderi

A simple way to do this would be:

一个简单的方法是:

let el = document.getElementById('slidesContainer');
el.innerHTML = `<div id='slideInner'>${el.innerHTML}</div>`;

回答by Will

From what I understand @Michal 's answer is vulnerable to XXS attacks(using innerHTML is a security vulnerability)Here is another link on this.

据我了解,@Michal 的回答容易受到 XXS 攻击(使用 innerHTML 是一个安全漏洞)这是另一个链接。

There are many ways to do this, one that I found and liked is:

有很多方法可以做到这一点,我发现并喜欢的一种方法是

function wrap_single(el, wrapper) {
    el.parentNode.insertBefore(wrapper, el);
    wrapper.appendChild(el);
}
let divWrapper;
let elementToWrap;
elementToWrap = document.querySelector('selector');
// wrapping the event form in a row
divWrapper = document.createElement('div');
divWrapper.className = 'row';
wrap_single(elementToWrap, divWrapper);

This works well. However for me, I sometimes want to just wrap parts of an element. So I modified the function to this:

这很好用。但是对我来说,有时我只想包装元素的一部分。所以我修改了这个函数:

function wrap_some_children(el, wrapper, counter) {
  el.parentNode.insertBefore(wrapper, el);
  if ( ! counter ) {
    counter = el.childNodes.length;
  }
  for(i = 0; i < counter;  i++) {
    wrapper.appendChild( el.childNodes[0] );
  }
}
// wrapping parts of the event form into columns
let divCol1;
let divCol2;
// the elements to wrap
elementToWrap = document.querySelector('selector');
// creating elements to wrap with
divCol1 = document.createElement('div');
divCol1.className = 'col-sm-6';
divCol2 = document.createElement('div');
divCol2.className = 'col-sm-6';
// for the first column
wrap_some_children(elementToWrap, divCol1, 13);  // only wraps the first 13 child nodes
// for the second column
wrap_some_children(elementToWrap, divCol2);

I hope this helps.

我希望这有帮助。

回答by viet nam

wrapInner multiple tag content

wrapInner 多标签内容



function wilWrapInner(el, wrapInner) {
  var _el = [].slice.call(el.children);
  var fragment = document.createDocumentFragment();
  el.insertAdjacentHTML('afterbegin', wrapInner);
  var _wrap = el.children[0];
  for (var i = 0, len = _el.length; i < len; i++) {
    fragment.appendChild(_el[i]);
  }
  _wrap.appendChild(fragment);
}


Link Demo Jsbin

链接演示 Jsbin