Change link

Hello,

i want to change a link of a breadcrumb in a wordpress cms and it won’t work…

Here’s the HTML

HTML Code:

<div class="breadcrumb">
    <ul>
        <li><a href="http://bo-institut.de">Home</a></li>
        <li class="category-detail"><a href="http://bo-institut.de/service/filler-hyaluron/" title="Service">Service</a></li>
        <li class="category-detail active"> <a href="http://bo-institut.de/service/filler-hyaluron/" title="Filler Hyaluron">Filler Hyaluron</a></li>        
    </ul>
</div>

The second link (Service) should be changed to ‘Ästhetik’ and should have a new href.

Here’s what i got:

<script>
var cont = document.getElementsByClassName('breadcrumb');
var el = cont.getElementsByClassName('ul')[1];
var link = el.getElementsByTagName('a');

link.innerHTML = "Ästhetik";
link.href = "http://bo-institut.de/aesthetik/";
</script>

Thank you for your help!

Check the console for errors. getElementsByClassName returns an array, not an element.

This is the error: (index):379 Uncaught TypeError: cont.getElementsByClassName is not a function

I changed something, because i found some mistakes. Here’s what i got now:

var
	breadcrumb = document.getElementsByClassName('breadcrumb')[1],
	ul = cont.getElementsByClassName('ul')[1],
	a = ul.getElementsByTagName('a')[1];

a.innerHTML = "Ästhetik";
a.href = "http://bo-institut.de/aesthetik/";

Now the console shows this error: Uncaught TypeError: Cannot read property ‘getElementsByTagName’ of undefined. I don’t know, what’s the issue

Hi @lulu68163, in programming languages the indices of collections generally start with zero, so given your markup, this

document.getElementsByClassName('breadcrumb')[1]

will return undefined.

You’ve got a few issues there:

  • cont is never defined because you changed the name.
  • ul and a aren’t class names so getElementByClassName won’t help you, getElementsByTagName will do what you want.
  • Combining them all into the single var declaration will not allow you to get the value of each so separate each onto their own lines.
  • indexes in JavaScript start at zero so I think you’re off by one on each.
var breadcrumb = document.getElementsByClassName('breadcrumb')[0];
var ul = breadcrumb.getElementsByTagName('ul')[0];
var a = ul.getElementsByTagName('a')[1];
a.innerHTML = "Ästhetik";
a.href = "http://bo-institut.de/aesthetik/";

Can be simplified using querySelector / querySelectorAll

var a = document.querySelectorAll('.breadcrumb a')[1];
a.innerHTML = "Ästhetik";
a.href = "http://bo-institut.de/aesthetik/";
2 Likes

Shouldn’t that be:

var a = document.querySelectorAll('.breadcrumb a')[0];

Nope.

Hello,

I was not sure if the simplification works. I’ll test it. Thank you

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.