简体   繁体   中英

Get parent div using href

Is is possible to find the parent div using just the href?

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. I am trying to find the parent element of these hrefs so that I can append a new div to that parents element. If this is not possible, what attribute would I need to be able to located the parent div of that attribute.

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 :

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:

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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