简体   繁体   English

在jQuery中查找嵌套元素的ID

[英]Find the ID of a nested element in jQuery

I have the following HTML code: 我有以下HTML代码:

<div id="div1">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div id="iwantthis"> </div>
</div>
  • The ID of the parent DIV will be always the same meaning #div1 won't change 父DIV的ID将始终相同,意味着#div1不会更改
  • The ID of the children DIV #iwantthis is generated dynamically 儿童DIV #iwantthis的ID是动态生成的

I need to get the value of that dynamic ID and I can't use .find() method since it's tied to a given selector. 我需要获取该动态ID的值,我不能使用.find()方法,因为它绑定到给定的选择器。 I have search for this and a lot of topics comes out but none fit my scenario (or at least I couldn't find it). 我已经搜索了这个并且出现了很多主题但是没有一个适合我的场景(或者至少我找不到它)。

What's the best way to find such ID value? 找到这样的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. 注意:除了帖子之外,请记住这一点:目前我将在当前持有动态ID之前有4个DIV,但这可能随时改变。

You can set context of jQuery() to #div1 , select child element having attribute [id] or specific id 您可以将jQuery() context设置为#div1 ,选择具有属性[id]或特定id子元素

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

If you know how many div s before the item, then you can use following selector. 如果你知道项目之前有多少个div ,那么你可以使用下面的选择器。

 var selector = "#div1>"; // loop 4 times, replace with how many div's before "wanted" div // of course it can be a variable for(var i = 0; i<4; i++) { selector += "div+"; } selector += "div"; console.log($(selector).attr("id")); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="div1"> <div></div> <div></div> <div></div> <div></div> <div id="iwantthis"> </div> </div> 

You can use the child selector relationship with attribute selector 您可以将子选择器关系与属性选择器一起使用

 var $target = $('#div1 > div[id]'); //use the id attribute to select the target element $target.addClass('selected'); //since the target is the last child you can use that relationship also $('#div1 > div').last().html('Using last child'); 
 .selected { background-color: lightgreen; } #div1 div { border: 1px solid grey; padding: 5px; margin-bottom: 5px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="div1"> <div></div> <div></div> <div></div> <div></div> <div id="iwantthis"></div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM