How to get the closest element id attribute

2019-03-04 05:11发布

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.

I have tried

element=$('#test').closest('div[id]').attr('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!

1条回答
冷血范
2楼-- · 2019-03-04 06:09

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

$('#test').closest('[id]').attr('id');
查看更多
登录 后发表回答