0

This is an exercise from a test.

I need to get the remove button working. I don't understand why the line

document.getElementsByClassName("remove")[0].click();

is there either

Here is the code

function setup() {
  // Write your code here.
}

// Example case. 
document.body.innerHTML = `
<div class="image">
  <img src="someimage.jpg" alt="First">
  <button class="remove">X</button>
</div>
<div class="image">
  <img src="someimage.jpg" alt="Second">
  <button class="remove">X</button>
</div>`;

setup();

document.getElementsByClassName("remove")[0].click();
console.log(document.body.innerHTML);

Edit: The expected output is that the remove button would remove the parent div (class="image")

user3808307
  • 2,270
  • 9
  • 45
  • 99

2 Answers2

1

It doesn't work because the "remove' button doesn't have a callback function for the click event defined for it.

Also, this: document.getElementsByClassName("remove")[0] should not be used as it causes a live node list to be created only to throw away that node list for just the first item in it. Instead, document.querySelector(".remove") should be used. See this other post of mine for details on this.

So, if we add a click event handler and clean up your code it will work:

function setup() {
  // Write your code here.
  
  // This will set up a callback function for when the remove button gets clicked:
  theRemoveButton.addEventListener("click", function(){
    console.log("You clicked the remove button!");
    this.closest(".image").remove();
  });
}

// Example case. 
document.body.innerHTML = `
<div class="image">
  <img src="someimage.jpg" alt="First">
  <button class="remove">X</button>
</div>
<div class="image">
  <img src="someimage.jpg" alt="Second">
  <button class="remove">X</button>
</div>`;

var theRemoveButton = document.querySelector(".remove");

setup();

theRemoveButton.click();  // Forces the click event to fire on the button
console.log(document.body.innerHTML);
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • document.getElementsByClassName("remove")[0] was in the test. I was wondering why they put that there, as it seems not to make any sense Is there a way to solve this writing code only where it says "Write you code" – user3808307 Mar 14 '19 at 15:01
  • @user3808307 Unfortunately, most teachers and courses on HTML, CSS and JavaScript are taught/written by people who don't really know and understand these languages. – Scott Marcus Mar 14 '19 at 15:02
1

I can't understand your problem but the

document.getElementsByClassName("remove")[0].click();

line simulate a click on the first element of the with a css class called "remove", so it's useless because no event are attached to this element. I think the addEventListener function is what your looking for.

Nil
  • 355
  • 1
  • 2
  • 8