简体   繁体   中英

Get Link from Parent Anchor to Div

How can I set div's onClick href to my parent anchor href value??

<a href="getThisLink.html" target="_parent">
    <img src="images/1.jpg" />
    <span>
    <div onclick="parent.location.href='**Link me with my anchor parent**' + 'params1';" >
           <span>Words Words Words</span>
    </div>            
</span>
</a>

Note : I'm using this with my slideshow.

The function updateHref() below takes a div element and looks for it's parent's parent tag. And ( only ) if it is an anchor ( <a> ) tag:

  • The onclick of the div will take the page to the <a> 's href plus urlParams .
  • The <a> href will now take to its old url plus urlParams .

Demo link here . Code below:

function updateHref(divElement, urlParams) {
    var parentAnchor = divElement.parentNode.parentNode;
    if (parentAnchor.nodeName != "A") return;
    var url = parentAnchor.href + urlParams;
    divElement.onclick = function() {
        parent.location.href = url;
    }
    parentAnchor.href = url; // override parent anchor href URL
}

Usage:

// for a specific div
var myDiv = document.getElementById('myDiv');
updateHref(myDiv, "search?p=param1");

// for all divs of the page (whose parent's parent is an anchor tag)
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++){
    updateHref(divs[i], "search?p=param1");    
}

Your code is not valid, but, here is the working script:

<a href="getThisLink.html" target="_parent">
    <img src="images/1.jpg" />
    <span>
        <div onclick="location.href = this.parentNode.parentNode.href + '#param1'; return false;">
            <span>Words Words Words</span>
        </div>
    </span>
</a>

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