如果div是特定div中的div并通过JQuery / Javascript将它们添加到集合中,如何捕获所有id?

时间:2022-03-02 15:16:45

I have the below HTML DOM:

我有以下HTML DOM:

<div class="carousel-inner" role="listbox">
<div class="item active" id="287"></div>
<div class="item" id="288"></div>
<div class="item" id="451"></div>
<div class="item" id="452"></div>
</div>

Now, using JQuery I want to create a collection which should look like:

现在,使用JQuery我想创建一个看起来像这样的集合:

var forms= {
    287:"0",
    288:"0",
    451:"0",
    452:"0"
};

Basically, I would like to update this collection later, making specific property values as "1" or something like this. Any help will be highly appretiated. Thanks in advance.

基本上,我想稍后更新此集合,使特定的属性值为“1”或类似的东西。任何帮助都会得到很高的评价。提前致谢。

2 个解决方案

#1


0  

If you are using jQuery, you can select a node's children and loop through them with each:

如果您使用的是jQuery,则可以选择一个节点的子节点并使用它们循环遍历:

var forms = {};
$('.carousel-inner').children().each(function(){
    var id = $(this).attr('id');
    if (id) {
        forms[id] = "0";
    }
});

You can also filter which children you want to select: by tag .children('div') or by class .children('.item')

您还可以过滤要选择的子项:标记.children('div')或类.children('。item')

#2


0  

See this:

var container = document.querySelector('.carousel-inner'),
    objectWithIds = {};

for (var i = 0; i < container.children.length; i++){
    if (container.children[i].id){
        objectWithIds[container.children[i].id] = "0"
    }
}

console.log(objectWithIds)

If you want only the DIV tags, change the if statement to container.children[i].id && container.children[i].tagName == "DIV"

如果只想要DIV标记,请将if语句更改为container.children [i] .id && container.children [i] .tagName ==“DIV”

#1


0  

If you are using jQuery, you can select a node's children and loop through them with each:

如果您使用的是jQuery,则可以选择一个节点的子节点并使用它们循环遍历:

var forms = {};
$('.carousel-inner').children().each(function(){
    var id = $(this).attr('id');
    if (id) {
        forms[id] = "0";
    }
});

You can also filter which children you want to select: by tag .children('div') or by class .children('.item')

您还可以过滤要选择的子项:标记.children('div')或类.children('。item')

#2


0  

See this:

var container = document.querySelector('.carousel-inner'),
    objectWithIds = {};

for (var i = 0; i < container.children.length; i++){
    if (container.children[i].id){
        objectWithIds[container.children[i].id] = "0"
    }
}

console.log(objectWithIds)

If you want only the DIV tags, change the if statement to container.children[i].id && container.children[i].tagName == "DIV"

如果只想要DIV标记,请将if语句更改为container.children [i] .id && container.children [i] .tagName ==“DIV”