用JS获取某个类型的父HTML元素 [英] Get the parent HTML element of certain type with JS

查看:514
本文介绍了用JS获取某个类型的父HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码看起来像这样,在特写中:

 < h2> 
< span class =stuff> [< a id =someid> stuff< / a>]< / span> < span class =moreStuff>另一个测试< / span>
< / h2>

我找到了一种方法来选择我的 a 元素,并附上一个id给它。我现在需要做的是选择其父< h2> 元素,但不要选择< span> 元素。编辑:当我检索选择的< a> s时,我该怎么做(JQuery允许)? ,我得到了他们的一个数组(我的页面上有很多这样的结构)。当我尝试编写 myArray [someIndex] .closest(h2)时,它表示元素没有 closest() code>方法。我将如何去解决这个问题?解析方案

一种方法是使用 .parents() jQuery方法,带有选择器。像这样的东西。

  $(#someid)。parents(h2); 

更新:

您可以使用 .closest() 带有选择器的方法,以仅获得与选择器匹配的最接近的父代。

  $(#someid)。最接近( H2); 

更新2:

用普通的JavaScript来做这件事会有点多。不知道它是否是最有效的,但一种方法是使用 document.getElementById()选择元素,然后通过<$ c获取对其父元素的引用$ c> parentNode 属性。那么你将不得不检查它是否是 h2 元素,如果不是,请查看该元素的父节点,等等。

您可以检查jQuery源代码,看看它们是如何实现最接近的方法的。


My code looks like this, in closeup:

<h2>
<span class="stuff">[<a id="someid">stuff</a>]</span> <span class="moreStuff">Another test</span>
</h2>

I've found a way to select my a element, and attach an id to it. What I need to do now is select its parent <h2> element, but not the <span> element. How can I do that (JQuery allowed)?

Edit: when I retrieve the selected <a>s, I get an array of them (there's lots of these structures on my page). When I try to write myArray[someIndex].closest("h2"), it says that the element does not have a closest() method. How would I go about this?

解决方案

One ways is to use the .parents() method of jQuery, with a selector. Something like this.

$("#someid").parents("h2");

Update:

You can use the .closest() method with a selector, to only get the closest parent that match the selector.

$("#someid").closest("h2");

Update 2:

It would be a bit more work to do it with plain JavaScript. Not sure if it is the most efficient, but one way would be to select the element with document.getElementById() and then get a reference to its parent through the parentNode property. Then you would have to check if it is an h2 element, and if not, look at that elements parent node, and so on.

You could check the jQuery source and see how they have implemented the closest method.

这篇关于用JS获取某个类型的父HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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