How to target the parent div from child div?

How to target & alter child element by tag with only the parent div id?

  • Using regular JavaScript (or prototype), I'm trying to alter the href attribute of the first and only anchor tag within a div to include a query string at the end with windows.location.search. The div has an id, while the anchor is classless and id-less. I've seen similar code elsewhere, but its not quite right. What I have so far is below: var divTag = document.getElementById("DivId").getElementsByTagName("a"); for(i = 0; i < divTag.length; i++){ divTags[i].href = "myUrl"+window.location.search; } The actual html code I"m tryin to work on: <div id="DivId"> <a href="OldHref"> <img/> </a> </div> Thank You.

  • Answer:

    You declare the variable as divTag but set the attribute as divTags.

SFox at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

Your code is largely correct. You just made a typo: divTags[i].href = "myUrl"+window.location.search; Should be: divTag[i].href = "myUrl"+window.location.search; Singular instead of plural.

Rob Sobers

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.