javascript - 在 jQuery 中查找嵌套元素的 ID

标签 javascript jquery

我有以下 HTML 代码:

<div id="div1">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div id="iwantthis"> </div>
</div>
  • 父 DIV 的 ID 将始终相同,这意味着 #div1 不会改变
  • 子DIV的ID#iwantthis是动态生成的

我需要获取该动态 ID 的值,但我不能使用 .find() 方法,因为它与给定的选择器相关联。我已经搜索过这个并且出现了很多主题,但没有一个适合我的场景(或者至少我找不到它)。

找到此类 ID 值的最佳方法是什么?

Note: In addition to the post keep this in mind: at the moment I will have 4 DIV before the current one holding the dynamic ID but this could change at any moment.

最佳答案

可以将jQuery()context设置为#div1,选择具有[id]属性的子元素 或特定的 id

var div = $(" [id]", document.getElementById("div1"));
var id = div.attr("id");

关于javascript - 在 jQuery 中查找嵌套元素的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40414206/

相关文章:

javascript - 在编译之前如何在多个文件之间共享全局 javascript 变量?

javascript - 使用 Javascript Ajax 将较长的 html 发布到 ASP.NET 页面时找不到页面

javascript - Bootstrap 'collapsed' 类未出现在 DOM 加载中

jQuery 图表

c# - "Object doesn' t 在IE8和IE7中支持这个属性或方法

javascript - 使用 jQuery Ajax 成功时显示脚本

javascript - ESLint:如何在文件中设置 "new-cap"规则的 "capIsNewExceptions"选项?

javascript - 对象解构赋值在构造函数中表现异常

javascript - IE8 中的 jQuery 动态表单创建无法处理大量数据

jquery - Firefox、Internet Explorer 和 Safari 像素宽度之间的奇怪差异