Search code examples
javascriptjqueryhtmljquery-mobile-collapsible

Create a collapsible div with javascript


I am trying to create a collapsible div but chrome console says 'undefined is not a function' on line attr data role collapsible. Can you tell me how to do this:

var iDiv = document.createElement('div');
iDiv.id = 'sectorDiv_'+distritoPosicion;
iDiv.className = 'sectorDiv_'+distritoPosicion;
iDiv.attr('data-role', 'collapsible');
iDiv.attr('data-collapsed-icon', 'arrow-r');
iDiv.attr('data-expanded-icon', 'arrow-d');
document.getElementsById('listaSectores')[0].appendChild(iDiv);

distritoPosicion is a numberand listaSectores is an existing div.


Solution

  • attr() is a method from jQuery, it's setAttribute() you are after.

    iDiv.setAttribute('data-role', 'collapsible');
    iDiv.setAttribute('data-collapsed-icon', 'arrow-r');
    iDiv.setAttribute('data-expanded-icon', 'arrow-d');
    

    Also you're trying to get your element the wrong way.

    document.getElementsById('listaSectores')[0]
    

    it's normally getElementById (no s at element) and it returns only one element so [0] is not needed in this case.

    document.getElementById('listaSectores').appendChild(iDiv);