Dynamically write search query to trackSiteSearch

I’m trying to retrieve the search query from a DOM element and write this string as “keyword” parameter in the trackSiteSearch function, but don’t get any reults.

On the search results page, the element where the search query is stored looks like this:
<ol class="search-results" data-query="search query">

So I’m trying to get the value of the data-query attribute and to do so, in the tracking snippet I added the following:

<script> var search_string = document.getElementsByClassName("search-results").getAttribute("data-query"); ... _paq.push(['trackSiteSearch', search_string]); ... </script>

If tested with a static keyword, e.g. “exampleSearchString”, it works fine and “exampleSearchString” appears in Piwik, but with the dynamic parameter, I only get “undefined”.

Do you have any hints what’s wrong here?