1

Could someone help me with a javascript that add a hyperlink to a list class? i.e. if class="backTo" then add href="index" to that class.

Current HTML

 <div class="secondary-nav">
        <ul class="secondary-nav">            
                <li class="backTo">Campaign</li>
                <li><a href="#" class="top">title 1</a></li>
                <li><a href="#" class="top">title 2</a></li>
                <li><a href="#" class="top">title 3</a></li>
                <li><a href="#" class="top">title 4</a></li>
        </ul>
    </div>

So the javascript does this:

 <div class="secondary-nav">
        <ul class="secondary-nav">            
                <li class="backTo"><a href="index">Campaign</a></li>
                <li><a href="#" class="top">title 1</a></li>
                <li><a href="#" class="top">title 2</a></li>
                <li><a href="#" class="top">title 3</a></li>
                <li><a href="#" class="top">title 4</a></li>
        </ul>
    </div>
Blaise
  • 13,139
  • 9
  • 69
  • 97
sierra.charli3
  • 205
  • 2
  • 22

1 Answers1

3

Add this at any place below the navigation, or include it in an external script:

<script>
    var backListItem = document.querySelector('.backTo');
    backListItem.innerHTML = '<a href="index">'+backListItem.innerHTML+'</a>';
</script>
Blaise
  • 13,139
  • 9
  • 69
  • 97
  • Use `textContent`, `innerText` won't work in Firefox: http://stackoverflow.com/questions/1359469/innertext-works-in-ie-but-not-in-firefox – Pavlo May 26 '15 at 09:36
  • @Pavlo That was in 2009, but if you need to support a really old version of Firefox, you could use `innerHTML` or `textContent` instead of `innerText`. – Blaise May 26 '15 at 09:39
  • Have you even tried it? Try to evaluate `document.body.innerText` in *any* version of Firefox – it will be `undefined`. – Pavlo May 26 '15 at 09:48
  • Tried it, I stand corrected :) will update my answer. – Blaise May 26 '15 at 10:07