如何获取最接近的元素id属性 [英] How to get the closest element id attribute

查看:141
本文介绍了如何获取最接近的元素id属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找具有id属性的最接近元素并获取id.元素可以是<p>, <div>或其他元素.

I am trying to find the closest element that has id attribute and get the id. The element could be <p>, <div> or other elements.

我尝试过

element=$('#test').closest('div[id]').attr('id');

,但仅在元素为div时才获取ID.我想变得更加普遍.反正有这样做吗?非常感谢!

but it only get the id if the element is a div. I want to be more universal. Are there anyways to do this? Thanks so much!

推荐答案

您可以完全摆脱div并查找具有id属性的所有元素:

You can get rid of the div entirely and look for all elements that have an id attribute:

$('#test').closest('[id]').attr('id');

这篇关于如何获取最接近的元素id属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆