Search code examples
jqueryhref

jQuery Problem: Can't read href attr for some reason


not sure why this is returning undefined. The element exists and I even tried to change the ID property to make sure it wasn't conflicting with anything in the namespace.

I also am importing jquery, so that's not the issue. The double brackets are for Django context variables

Any thoughts?

<script type="text/javascript">

//return to search page with appropriate GET parameters
var parameters=window.location.search +'';

$('#back').attr('href',$('#back').attr('href')+parameters);



</script>   

<div id="content"> 
<a id="back" href="{{site}}search/"><< Return to Search Results </a>
</div>

Solution

  • Make sure you're modifying the attribute after the DOM is fully loaded by putting your code inside a call to $(document).ready():

    <script type="text/javascript">
        $(document).ready(function()
        {
            var parameters=window.location.search +'';
            $('#back').attr('href',$('#back').attr('href')+parameters);
        });
    </script>
    

    The code as it appears in your question will fail if the script tag is inside the body, because the Javascript will be invoked as it's parsed, and at that point in time, your anchor tag has yet to be parsed.