如何动态获取html元素的id

How to get the id of and html element dynamically?

本文关键字:html 元素 id 获取 何动态 动态      更新时间:2023-09-26

我有以下结构:

<input name="20735" class="form-control valid-dateonly error" id="20735" required="" type="text" maxlength="4000" placeholder="" value="">
<label class="error" style="left: 0px; white-space: nowrap; position: absolute;" for="20735">This field is required.</label>
<span class="input-group-addon">            
    <span class="fa fa-calendar"></span>
</span>
<div id="div_20735"></div>

基本上,我在JQuery $this中有标签控件。现在我想用id:div_20735来捕获div。如果您观察,这个20735也是输入控件的id,它位于标签上方。我猜是$(this).prev().id之类的…但是我没有得到。但我得到这个值(20735),当我做$(this).prev().context.htmlfor ..但我认为这不是最好的找回方法。这是我尝试过的:

 $('label.error').not('.hide').each(function () {
    var previousElm = $(this).prev();
    if ($(previousElm).hasClass("form-control")) {
        $("#div_20735").after($(this));//here I need help to capture the id of the div dynamically
        $(this).css({ 'position': 'absolute', 'white-space': 'nowrap', 'left':'0px' });
    }           
});

任何帮助找到最好的方法将是高度赞赏的。谢谢。

试试这个-它取for属性值,这是你需要的

$('label.error').not('.hide').each(function () {
    var previousElm = $(this).prev();
    if ($(previousElm).hasClass("form-control")) {
      var divID = $(this).attr('for');
      $("#div_" + divID).after($(this));//here I need help to capture the id of the div dynamically
      $(this).css({ 'position': 'absolute', 'white-space': 'nowrap', 'left':'0px' });
    }           
});

这个$("#div_" + previousElm.attr('name'))应该可以做到:

$('label.error').not('.hide').each(function () {
    var previousElm = $(this).prev();
    if ($(previousElm).hasClass("form-control")) {
        $("#div_" + previousElm.attr('name')).after($(this));//here I need help to capture the id of the div dynamically
        $(this).css({ 'position': 'absolute', 'white-space': 'nowrap', 'left':'0px' });
    }           
});