1

I have a div that has notes within it (each note has a title and content). When creating a new note, it gets its own title and content added into this div.

<div class="notes-list">
  <h4 class="note-title">Title</h4>
  <input class="note-content">Note content</input>
</div>

How can I make the input hide/show when I click on the title related to it?

const titles = document.querySelectorAll(".note-title");
const noteContent = document.querySelectorAll(".note-content");

titles.forEach(function(title) {
  title.addEventListener("click", () => {
    // unsure how to select the corresponding input related to the title:
    noteContent.style.display = "inline-block";
  });
});
  • 1
    Have you tried a jQuery `.toggle()` method? It toggles between `.hide()` & `.show()` – BeerusDev Jul 15 '21 at 13:25
  • 1
    I'm trying to do this without using jQuery (we are building a note app with only html, css and vanilla js) – Ashley Slaney Jul 15 '21 at 13:28
  • I think toggle is not jQuery only. It should work also in pure JS. Check https://www.w3schools.com/howto/howto_js_toggle_class.asp – Gergo Jul 15 '21 at 13:43
  • Have you tried `noteContent.style.display = noteContent.style.display === "inline-block" ? "none" : "inline-block";` –  Jul 15 '21 at 13:44

1 Answers1

0

Your not that far off. Just a few changes necessary. Since querySelectorAll returns a nodeList you cannot access your element directly, instead we can use the index from our forEach to find the correct element.

The easiest method to toggle elements would be to use a CSS class together with classList.toggle(). Another option could be to check its display style and change the property accordingly.

As a side note: An input element is selfclosing meaning the </input> is obsolete. If you want to give it a label use as the name suggests the label element. More info on closing an input tag in this thread.

const titles = document.querySelectorAll(".note-title");
const noteContent = document.querySelectorAll(".note-content");

titles.forEach(function(title, index) {
  title.addEventListener("click", () => {
    // unsure how to select the corresponding input related to the title:
    noteContent[index].classList.toggle("hide");
  });
});
.hide {
  display: none;
}
<div class="notes-list">
  <h4 class="note-title">Title 1</h4>
  <label>
    <input class="note-content">
    Note content 1
  </label>
  
  <h4 class="note-title">Title 2</h4>
  <label>
    <input class="note-content">
    Note content 2
  </label>
  
  <h4 class="note-title">Title 3</h4>
  <label>
    <input class="note-content">
    Note content 3
  </label>
</div>
Reyno
  • 6,119
  • 18
  • 27