Search code examples
javascriptadobeadobe-analytics

Retrieve name value from button in javascript


I have the following HTML:

<div class="dropdown" data-offers-filter-segments="">
  <button class="toggle--dropdown" name="toggle-segment-cagetories-list">
     <span class="dropdown__label" id="dropdown__labelAllCategories">All Categories</span>
  </button>
<div class="dropdown__content" hidden="hidden">

Which renders a dropdown, when clicked a new class is appended which is called is-dropped so the parent div will look like this once its been clicked on class="dropdown is-dropped"

Now using Javascript I'm trying to retrieve name="toggle-segment-cagetories-list" which we will use within DTM (Adobe Tag Manager) as an eVar value but I'm uncertain how I go about retrieving that name value, so far I have the following javascript:

function hasClass(element, cls) {
    return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}

if(hasClass(document.getElementsByClassName('dropdown')[0], 'is-dropped')){
// Now get the name value ? 
}
else {
  alert("false");
}

Now I'm pretty new to javascript so if someone can shed some light in how I go about getting the name value and passing it to DTM I would highly appreciate it.


Solution

  • use document.querySelector:

    <div class="dropdown is-dropped" data-offers-filter-segments="">
      <button class="toggle--dropdown" name="toggle-segment-cagetories-list">
         <span class="dropdown__label" id="dropdown__labelAllCategories">All Categories</span>
      </button>
    <div class="dropdown__content" hidden="hidden">
    
    <script>
    var button=document.querySelector('div.is-dropped button.toggle--dropdown');
    var name=button&&button.name||'';
    alert(name);
    </script>