Skip to content

how to remove class of a specific element inside an element

function myfunction() {
  let items = document.querySelectorAll("#ol li"),
    array = [];
  for (var i = 0; i < items.length; i++) {
    array.push(items[i].innerHTML);
  }

  for (var i = 0; i < items.length; i++) {
    items[i].onclick = function() {
      document.getElementById("content").innerHTML = this.innerHTML;
    }
  };
}
<ol id="ol">
  <li class="li">
    <span class="x">hello</span>
    <span class="xx">testing</span>
  </li>
  <li class="li">
    <span class="x">hello2</span>
    <span class="xx">testing2</span>
  </li>
  <li class="li">
    <span class="x">hello3</span>
    <span class="xx">testing4</span>
  </li </ol>

  <div id="content"></div>

  <button onclick="myfunction()">click</button>

When I click on one of the lists, the code will put the innerHTML of the list that I clicked into a div, but I also want to remove the class of the spans in the list that is inside the div

How can I do this?

ive tried this but it doesnt work

 function myfunction() {
      let items = document.querySelectorAll("#ol li"),
        array = [];
      for (var i = 0; i < items.length; i++) {
        array.push(items[i].innerHTML);
      }

      for (var i = 0; i < items.length; i++) {
        items[i].onclick = function() {
         document.getElementById("content").innerHTML = this.innerHTML;

        const spanInsideDiv = document.querySelector("#content .li .x")
        for (var i = 0; i < spanInsideDiv.length; i++) {
               spanInsideDiv[i].classList.remove('li');
        }
      };
    }

Answer

At the moment your simply copying all the innerHTML to the target <div>. After this happened we can get a HTMLCollection – more or less an array – of all the <span> elements inside using:

document.getElementById("content").getElementsByTagName("span");

Now we can simply loop over the collection and remove all the css classes by calling removeAttribute("class") on each one. This will remove any css class while keeping your original spans intact.

Here’s an example:

function myfunction() {
  let items = document.querySelectorAll("#ol li"),
    array = [];
  for (var i = 0; i < items.length; i++) {
    array.push(items[i].innerHTML);
  }

  for (var i = 0; i < items.length; i++) {
    items[i].onclick = function() {

      document.getElementById("content").innerHTML = this.innerHTML;
      let span = document.getElementById("content").getElementsByTagName("span");

      for (var a = 0; a < span.length; a++) {
        span[a].removeAttribute("class");
      }
    }
  };
}
<ol id="ol">
  <li class="li">
    <span class="x">hello</span>
    <span class="xx">testing</span>
  </li>
  <li class="li">
    <span class="x">hello2</span>
    <span class="xx">testing2</span>
  </li>
  <li class="li">
    <span class="x">hello3</span>
    <span class="xx">testing4</span>
  </li>
</ol>

<div id="content"></div>

<button onclick="myfunction()">click</button>