如何获取 <div> 中不同元素的所有 id 属性?

How can I get all the id properties of the different element inside a <div>?

假设我的网页上有一个 <div>,里面有不同的标签,例如 <p><label><span> 等等,所有这些有一个唯一的 ID 属性。在 javascript 上,如何获取 <div> 中元素的 ID?

例如:

<div id = "cont">

<p id = '0001'>
Prod One
</p>

<label id = '0002'>
Prod Two
</label>


<p id = '0003'>
Prod Three
</p>


<span id = '0004'>
Prod Four
</span>


</div>

<button onclick = 'getIDsInsideDiv()'>Get The ID of the elements inside the div </button>

如果我要点击按钮,它会输出:

0001, 0002, 0003, 0004

尝试 querySelectorAll 执行基于 CSS 样式选择器的查询。

在这里,我将使用 #cont [id] 来获取所有具有 id 属性且属于 #cont.

子元素的元素
var elements = document.querySelectorAll('#cont [id]'),
    ids = Array.prototype.map.call(elements, function(element) {
        return element.id;
    });

请记住,这是对 #cont 下元素的递归搜索。如果您不想检索嵌套元素(即,您只想要直系子元素),请使用 #cont > [id].

我在这里使用 Array.prototype.map.call,因为 querySelectorAll 返回的 NodeList 就像一个数组,但没有像 map() 这样的方法。参见 NodeList - Why is NodeList not an Array?

JSFiddle 演示 ~ http://jsfiddle.net/qykfv6Lp/