简体   繁体   English

使用href获取父div

[英]Get parent div using href

Is is possible to find the parent div using just the href? 是否可以仅使用href查找父div?

I basically have the following function: 我基本上具有以下功能:

var hrefs = [];
[].forEach.call(document.querySelectorAll("area"), function (value, index, array) {
    hrefs.push(value.getAttribute("href"));
});

for (var i = 0; i < hrefs.length; i++) {
    console.log(hrefs[i]);
    }

which finds all hrefs that belong to a html area. 查找属于html区域的所有href。 I am trying to find the parent element of these hrefs so that I can append a new div to that parents element. 我试图找到这些href的父元素,以便可以将新的div附加到该父元素。 If this is not possible, what attribute would I need to be able to located the parent div of that attribute. 如果这不可能,那么我需要什么属性才能定位该属性的父div。

You want something like this?: 您想要这样的东西吗?:

var hrefs = document.querySelectorAll("area");

for (var i = 0; i < hrefs.length; i++) {
    console.log(hrefs[i].getAttribute('href'));
    console.log(hrefs[i].parentNode);
}

First create an object with all those elements: 首先创建一个具有所有这些元素的对象:

var hrefs = {};

Array.prototype.forEach.call(document.querySelectorAll("area[href]"), function (element) {
    hrefs[ element.getAttribute("href") ] = element;
});

Then you can get to their parent by using .parentNode : 然后,您可以使用.parentNode到达其父.parentNode

for ( var i in hrefs ) {
    console.log( i, hrefs[i].parentNode );
}

So, if you want to later add an element to the parent of http://www.google.com , you could do this: 因此,如果您以后想要将元素添加到http://www.google.com的父级,则可以执行以下操作:

hrefs['http://www.google.com'].parentNode.appendChild( element );

I cannot see why you wouldn't just: 我不明白为什么你不只是:

[].forEach.call(document.querySelectorAll("area"), function(area) {
    area.parentNode.appendChild(
        document.createElement("div")
    );
});

The strategy is to get all the area elements, then match on their href value. 策略是获取所有区域元素,然后匹配其href值。 The following returns the first matching area element: 以下内容返回第一个匹配的area元素:

function getAreaByHref(href) {
  var areas = document.getElementsByTagName('area');
  for (var i = 0, iLen=areas.length; i<iLen; i++) {
    if (areas[i].href == href) {
      return areas[i].parentNode;
    }
  }
}

If you think there will be more than one, have the function build an array of matched elements and return that. 如果您认为会有不止一个,请让该函数构建一个匹配元素的数组并将其返回。

如果使用jQuery,则可以使用.parent()方法来完成此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM