I am trying to change the link of a basic <a>. It has no id. It is located in a header.aspx file that I cannot access directly. It is also the first grandchild element of a div with the id “SiteMenu”. From that div I would like to use the following script. (I can put script refs in the footer and upload to the Theme dir):
document.getElementById("SiteMenu").childNodes[0].childNodes[0].href = "/search.aspx?keyword='+'&page=1";`
also tried:
document.getElementById("SiteMenu").firstChild.childNodes[0].href = "/search.aspx?keyword='+'&page=1";`
The basic structure of the HTML is:
<div id="SiteMap">
<p>
<a href="/home.aspx">Home</a>
</p>
</div>
I’m no JS pro. From some things I read before posting here, it seems like childNodes.childNodes is an invalid way to search through node levels in JS (or the DOM?).
Is there some other way to manipulate the href of my tag?
.childNodes[0]won’t have any children since the first child is a text node, containing the line break and space before the<p>(at least in your example). You want to get the first element node.For example:
See
.children[MDN] for more information.Alternative you can iterate over each child node and test its
.nodeType[MDN] to see whether it is an element node or not.