Search code examples
javascripthtmlprototypejsparent-childgetelementsbytagname

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.


Solution

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