Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/466.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取指定父级之前的所有父级信息_Javascript_Jquery_Html_Dom_Parents - Fatal编程技术网

Javascript 获取指定父级之前的所有父级信息

Javascript 获取指定父级之前的所有父级信息,javascript,jquery,html,dom,parents,Javascript,Jquery,Html,Dom,Parents,我有一个html代码示例: <html> <body> <div> <div id="stophere"> <h4 class="parentclass"> <span class="target">Clicked</span> </h4>

我有一个html代码示例:

<html>
    <body>
        <div>
            <div id="stophere">
               <h4 class="parentclass"> 
                <span class="target">Clicked</span>
               </h4>
            </div>
        </div>
    </body>
</html>
但它包含了所有家长的标签名。而我想要的结果只有1个div和1个h4

让target的所有父对象从stophere下来的正确方法是什么?

您可以使用该方法

$(ev.target).parentsUntil($('#stophere').parent())
请注意,它是非包容性的,因此我们传递stophere的父元素以包括该元素


我并不认为这是一个好的解决方案,但如果adeneo的解决方案在您的情况下失败,比如我的情况,那么可以使用它

此代码使用find方法检查遍历限制是否包含该限制线本身:


不确定为什么在我的案例中使用映射和事件处理程序时它不起作用。但是在js小提琴中工作得很好
$(ev.target).parentsUntil($('#stophere').parent())
    jQuery('html').on("click", function (ev) {
        var elemparentid = jQuery(ev.target).closest("[id]").attr("id");
        var thisparents = jQuery(ev.target).parents()
            .map(function () {
// check if traversing limit is a children of current element or not, by using find() method
            if (jQuery(this).find("#" + elemparentid).length < 1) {
                return this.tagName;
            }
        }).get()
            .join(", ");
        alert(thisparents);
    });