0

是否可以仅使用 href 找到父 div?

我基本上有以下功能:

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]);
    }

它查找属于 html 区域的所有 href。我正在尝试找到这些 href 的父元素,以便可以将新的 div 附加到该父元素。如果这是不可能的,我需要什么属性才能找到该属性的父 div。

4

5 回答 5

1

你想要这样的东西吗?:

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

for (var i = 0; i < hrefs.length; i++) {
    console.log(hrefs[i].getAttribute('href'));
    console.log(hrefs[i].parentNode);
}
于 2013-06-26T23:53:27.453 回答
0

The strategy is to get all the area elements, then match on their href value. The following returns the first matching area element:

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.

于 2013-06-27T00:01:22.967 回答
0

首先创建一个包含所有这些元素的对象:

var hrefs = {};

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

然后您可以使用以下方式找到他们的父母.parentNode

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

因此,如果您想稍后向 的父级添加一个元素http://www.google.com,您可以这样做:

hrefs['http://www.google.com'].parentNode.appendChild( element );
于 2013-06-26T23:54:35.187 回答
0

我不明白你为什么不这样做:

[].forEach.call(document.querySelectorAll("area"), function(area) {
    area.parentNode.appendChild(
        document.createElement("div")
    );
});
于 2013-06-26T23:56:48.427 回答
-2

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

于 2013-06-26T23:51:29.287 回答