javascript - 将 div 的子级插入 javascript 数组

标签 javascript jquery html

我有一个 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"]

最佳答案

您所做的事情是正确的,除了 this 是一个元素实例。因此,为了调用 html(),您需要通过 $(this) 将其设为 jQuery 实例。尝试下面的代码。

let arr = [];

$("#parent div").each(function() {
  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">
  <div>child 1</div>
  <div>child 2</div>
</div>

关于javascript - 将 div 的子级插入 javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58550257/

相关文章:

javascript - 缩小溢出的内容以适应容器?

javascript - React : You may need an appropriate loader to handle this file type, 当前没有配置加载程序来处理此文件(本地 Node 模块)

javascript - 检查图像是否存在而不加载它

javascript - Rails - 具有不显眼的 javascript Jquery UI 进度条的 Ajax

jQuery 不设置 CSS 属性

javascript - 使用 ajax 在 bootstrap carousel 上附加数据

javascript - 无法使用 JS 更改 IE 中的属性值

javascript - Mongoose 无法从 MongoDB 数据库获取数据

javascript - Div 中的内联内容

html - 我怎样才能收缩图像以适应 parent 设定高度内的所有 flex child