roybalderama
roybalderama

Reputation: 1640

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.

Upvotes: 0

Views: 1513

Answers (2)

acdcjunior
acdcjunior

Reputation: 135862

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

Upvotes: 2

Chris
Chris

Reputation: 21

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>

Upvotes: 0

Related Questions