Skip to content

Getting an undefined error when trying to pull the URL from my css using JS

I thought I got this one right, apparently not as I’m getting an “undefined” error

Here is my CSS

<main id="tm-content" class="tm-content">
<ul class="uk-breadcrumb">
<li>
<a href="/countries">Countries</a>
</li>
<li>
<a href="/countries/united-states">United States</a>
</li>

Will this bit of javascript define https://www.example.com/countries ?

    function getHref() {
  return $('.uk-breadcrumb li a')[0].href
}

enter image description here

Any suggestions or guidance would be very much appreciated

Answer

It looks like you might not have the $ defined.

For this simple case, you should be able to use document.querySelectorAll in its place:

function getHref() {
  return document.querySelectorAll('.uk-breadcrumb li a')[0].href;
}

alert(getHref());
<ul class="uk-breadcrumb">
<li>
<a href="/countries">Countries</a>
</li>
<li>
<a href="/countries/united-states">United States</a>
</li>

Note that this doesn’t have full support below IE9, if you need that then i’d recommend jQuery.