将 div 的子级推送到 javascript 数组

我有一个div里面有一些子元素。我正在尝试遍历div并将每个孩子推送到一个对象数组,但我不知道如何遍历div.

我试过了

$("#id").children('div').each(function(){arrayName.push(this.html)}

没有运气。这是我到目前为止所拥有的。

$("#todocontentInner").children('div').each(function() { 
   oldContent.push(this.html());
            });

我希望 oldcontent 等于这样的东西

["<div class="contentitem">Bob</div>", "<div class="contentitem">Joe</div"]


临摹微笑
浏览 176回答 3
3回答

倚天杖

你不需要jQuery:const arr = [...document.querySelectorAll('#someID > div')].map(el => el.innerHTML);console.log(arr);<div id="someID">&nbsp; <div>1</div>&nbsp; <div>2</div>&nbsp; <div>3</div>&nbsp; <div>4</div>&nbsp; <div>5</div>&nbsp; <div>6</div></div>

慕哥9229398

澄清一下:this返回一个原生 DOM 元素,而$(this)将返回其等效的 jQuery 元素。与.html()jQuery 方法一样,它仅适用于 jQuery 元素,而不适用于本机 DOM 元素。因此,要获取元素的 HTML,您必须使用this.innerHTML或$(this).html()。然而; 它仍然不会产生您期望的结果。要推送子元素的完整 HTML,您需要推送它们outerHTML。TLDR;通过使用以下方法推送本机 DOM 元素的 HTML,您将获得预期结果this.outerHTML:$("#id").children('div').each(function(){arrayName.push(this.outerHTML)})或者,如果您真的想使用 jQuery,您将获得相同的结果$(this).prop('outerHTML'):$("#id").children('div').each(function(){arrayName.push($(this).prop('outerHTML'))})您可以在此处查看工作示例:let arrayName = []$("#id").children('div').each(function(){arrayName.push(this.outerHTML)})console.log("First approach: ", arrayName)let arrayName2 = []$("#id").children('div').each(function(){arrayName2.push($(this).prop('outerHTML'))})console.log("Second approach: ", arrayName2)<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="id">&nbsp; <div class="contentitem">Bob</div>&nbsp; <div class="contentitem">Joe</div></div>

慕容森

你在做什么是正确的,除了它this是一个元素实例。因此,为了调用 ,html()您需要将其设为 jQuery 实例$(this)。试试下面的代码。let arr = [];$("#parent div").each(function() {&nbsp; arr.push($(this).html());});console.log(arr);<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script><div id="parent">&nbsp; <div>child 1</div>&nbsp; <div>child 2</div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript