Search code examples
javascripthtmltargeting

How can I target a div on my HTML page with Javascript to change the contents of an element?


I've got an interesting question. I'm running Squarespace @ buscadprimero.caminoglobal.org and need to target the top-right button on the navigation (Ingresar, which means login) to bring up a Javascript form provided to me via embed code. The code itself works fine when included as a code block in the body of a page, but Squarespace only allows navigation buttons at the top to be hyperlinks. There's nowhere for me to add code to the button itself, being that it is a largely consumer platform and works great for straightforward application until you try to change the way it works.

They make an allowance for custom code via a "code injection" menu that adds whatever code you want to the HTML header of the page, so I've been trying to target this div, which does not have an id but who's class is external, with Javascript to replace its contents with an onclick listener to bring up this form. Tracking?

Here's my embed code, which like I said is fine:

<script>// <![CDATA[
   !function(e,t){e._cc={}, e._cc.host="https://www.coachingcloud.com/";var n=function(){var n=t.createElement("script"),c=t.getElementsByTagName("script")[0];n.src=e._cc.host+"login.min.js",c.parentNode.insertBefore(n,c)};e.addEventListener?e.addEventListener("load",n,!1):e.attachEvent("onload",n)}(window,document);
// ]]></script>

I've been trying document.getElementsByClassName("external").innerHTML; but when set to a var that returns undefined. New to Javascript but not afraid to learn. I'd like to figure out how to properly target the div, first of all, and then replace its contents (which currently is a link to my 404 page) with a Javascript function that activates on click. Thanks for the guidance!


Solution

  • Thanks to the great help of @Arg0n, I've now got a working login form that appears in the top-right-most button of my site. Using:

    $(function() { $("#mainNavigation .collection").last().html("<span id='cc-login'>Ingresar</span>"); });

    as the function to replace the contents of the div in question, I inserted <span id='cc-login'>Ingresar</span> as the call to the provided embed code:

    <![CDATA[ !function(e,t){e._cc={}, e._cc.host="https://www.coachingcloud.com/";var n=function(){var n=t.createElement("script"),c=t.getElementsByTagName("script")[0];n.src=e._cc.ho‌​st+"login.min.js",c.parentNode.insertBefore(n,c)};e.addEventListener?e.addEventLi‌​stener("load",n,!1):e.attachEvent("onload",n)}(window,document); // ]]>

    Turns out that a little jQuery was helpful in accessing the desired div, and setting its html contents was a bit beyond my area of expertise.

    Many thanks to the StackOverflow community for helping me learn about targeting page elements with Javascript to procedurally manipulate its contents.