Skip to content
Advertisement

Switch paragraphs using inner HTML in JS

I am trying to switch two paragraphs after clicking the button but I am stuck. Is there any way how to do this using inner HTML without using IF or boolean? I tried this code but it doesn’t work. Thanks

let elmsButton = document.querySelectorAll("button")[0];
let elmsParagraf1 = document.querySelectorAll(".prvni")[0];
let elmsParagraf2 = document.querySelectorAll(".druhy")[0];

elmsButton.addEventListener("click", () => {
    elmsParagraf1.innerHTML = "<div class='druhy'></div>"
    elmsParagraf2.innerHTML = "<div class='prvni'></div>"
});

Advertisement

Answer

Why don’t you use querySelector in place of using querySelectorAll and choose the first element?

By the way, I advise to delete and re-add the elements from the parent rather than using innerHTML. The use of innerHTML would not preserve listeners and have worse performances:

let elmsButton = document.querySelector("button");
let elmsParagraf1 = document.querySelector(".prvni");
let elmsParagraf2 = document.querySelector(".druhy");

elmsButton.addEventListener("click", () => {
    swapElements(elmsParagraf1, elmsParagraf2);
});

function swapElements(elem1, elem2) {
  // Check if siblings
  if (elem1.parentElement !== elem2.parentElement) {
    console.error('No sibling elements!');
    return;
  }
  elem1.replaceWith(elem2.cloneNode(true));
  elem2.replaceWith(elem1.cloneNode(true));
}

Example:

let elmsButton = document.querySelector("button");

elmsButton.addEventListener("click", () => {
    let elmsParagraf1 = document.querySelector(".prvni");
    let elmsParagraf2 = document.querySelector(".druhy");
    swapElements(elmsParagraf1, elmsParagraf2);
});

function swapElements(elem1, elem2) {
  // Check if siblings
  if (elem1.parentElement !== elem2.parentElement) {
    console.error('No sibling elements!');
    return;
  }
  elem1.replaceWith(elem2.cloneNode(true));
  elem2.replaceWith(elem1.cloneNode(true));
}
<button>Click me</button>

<div class="prvni">I am the first div</div>
<div class="druhy">I am the second div</div>
Advertisement