Search code examples
javascriptdom-manipulation

Get the child element and modify the text


I need to toggle the text in the span element from [+] to [-] when the button is clicked with JavaScript. How can I achieve this with my current toggle function?

HTML

...
<ul>
  ...
  <li>
    <ul>
      <h3>header</h3>
      <a href="#">url-link</a>
      <p>description</p>
    <ul>
    <div class="department" style="display: none;">
      <ul class="placemark"> ... </ul>
      <ul class="contact"> ... </ul>
    </div>
    <button class="department-collapse" onclick="toggle(this)">
      <span>[+]</span> Contact Information
    </button>
  </li>
  ...
<ul>
...

JavaScript

function toggle(self) {
  var n = self.parentNode.childNodes;
  
  for(var i = 0; i < n.length; i++) {
    if (n[i].className == 'department') {
      n[i].style.display = n[i].style.display == '' ? 'none' : '';
    }
  }
}

Solution

  • Inside your function, verify your span (JS code):

    function toggle(self) {
        var n = self.parentNode.childNodes;
    
        for(var i = 0; i < n.length; i++) {
            if (n[i].className == 'department') {
                n[i].style.display = n[i].style.display == '' ? 'none' : '';
            }
        }
    
        var mySpan = self.childNodes[0];
        mySpan.innerHTML = mySpan.innerHTML == '[+]' ? '[-]' : '[+]';
    }