如何动态获取html元素的id
How to get the id of and html element dynamically?
我有以下结构:
<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' });
}
});
相关文章:
- 如何设置html元素填充的动画
- 删除对HTML元素的拖动
- 如何使用jquery迭代具有相同属性的html元素并查找onclick事件
- 如何使用JQuery在Javascript中转换字符串中的HTML元素
- 一个html元素的克隆次数太多
- 使用AngularJS Directive WHITOUT$scope创建一个动态html元素
- 为什么我在Internet Explorer上看不到html元素
- 重新排列HTML元素的顺序并更改内容
- 使用.on动态添加jquery/js不知道的html元素
- 如果类不是一个选项,如何在使用 jQuery 时控制(避免)嵌套 html 元素的样式
- 如何将html元素添加到tampermonkey中
- 访问html元素值javascript
- 如何在HTML元素上创建函数,而不是将元素作为参数传递
- 自定义HTML元素属性未显示-Web组件
- 让HTML元素充当停止滚动的锚点
- 将html元素插入到文本字符串中,以匹配另一个html字符串
- 替换HTML元素中的字符
- 如何将html元素添加为生成的内容
- 如何使用JavaScript在没有html dom的情况下隐藏html元素
- 使用JS加载HTML元素