Given a dom element, how could I flatten it in jquery and/or JavaScript?

╄→гoц情女王★ 提交于 2019-12-08 05:01:09

问题


Let's say I get an element from the dom:

[<div id="generic-wrapper"> ... </div>]

How could I flatten it to include all elements inside?

EDIT: "generic-wrapper" is an arbitrary id, it could be anything. It could also be nested, as in wrappers within wrappers.

EDIT2: I want the final array to include all of the content of the original array, just flattened. This includes the wrapper. Is there a systematic way to construct and iterate through an array such as the one I am describing? Thanks again and apologies for the confusion.


回答1:


Select them all at once:

var $allElements = $("#wrapper,#wrapper *")

I'm not sure if you want to exclude the wrapper element itself, but if so just use "#wrapper *".




回答2:


Update:

'Simple' solution:

var domElements = [<div id="generic-wrapper">...</div>];

$.merge( domElements, $(domElements).find('*'));



Better solution:

It sounds like what you're trying to do is, given an array of dom elements, add each of their descendants to the array. If you're using jQuery for the intended DOM manipulation, you should just select them directly (as shown in code sample below). This returns a jQuery object, which has an underlying array structure that you can use for basic array-indexing. If you need to get a true array, you can use the object's .toArray() method. The jQuery object is typically more useful though, since you can manipulate all matched elements easily (and you can also iterate over them using .each()).

Select #wrapper and all of its descendants (if id is stored in a variable, replace '#wrapper' with '#' + the variable name.)

var domElements = $('#wrapper, #wrapper *');



回答3:


An HTML string?

$('<div>').append($('#wrapper').clone()).html();



回答4:


Here's one where you don't have to know the id of the parent selector when you flatten the selection:

var x = $('selector for the parent element');
var y = x.add($('*', x));

How it works:

Let's say you had an html structure like this:

<div id="foo">
  <ul>
    <li></li>
  </ul>
</div>

So the first line, var x = $('#foo') selects the wrapper.

The second line, var y = x.add($('*', x)) will take your selection of the wrapper and add to it a recursive selection of every element contained inside the wrapper. The end result looks like this:

[<div id="foo">...</div>, <ul>...</ul>, <li></li>]


来源:https://stackoverflow.com/questions/11875684/given-a-dom-element-how-could-i-flatten-it-in-jquery-and-or-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!