3

I want to hide and show div's that are created dynamically. I create the divs by pushing the button Category.

<button id="Category">Add category</button>

And then use jquery to add that div to the DOM with the following function, so every time i want to hide and show this div I just click the button.

$(document).ready(function () {
   $("#Category").click(function () {
   var categoria = prompt("Introduce el nombre de la categoria");
   nombreCategoria = categoria;
   $("#Productos").append('<div id=' + '"' + categoria + '"' + '><br><button onclick=' + '"' + 
 category+ '()"' + '>' + categoria + '</button></div>');
 });
});

But my problem is i don't know how to get the id of the dynamically created div, so that every time I push click on the name of any create div it would hide or show.

I used the following function to hide and show a div that was already created, but this doesn't work on the divs that are created dynamically.

function category() {
  var x = document.getElementById("ordenadores");
  if (x.style.display === "none") {
   x.style.display = "block";
  } else {
  x.style.display = "none";
 }
}

Any help would be appreciated.

Mario Muresean
  • 233
  • 1
  • 5
  • 16

1 Answers1

1

With your example you could just pass the id into the function like so:

$(document).ready(function () {
   $("#Category").click(function () {
   var categoria = prompt("Introduce el nombre de la categoria");
   nombreCategoria = categoria;
   $("#Productos").append('<div id=' + '"' + categoria + '"' + '><br><button onclick=' + '"' + 
 category+ '("' + categoria + '")"' + '>' + categoria + '</button></div>');
 });
});

Then you could just read it like this:

function category(catId) {
  var x = document.getElementById(catId);
  if (x.style.display === "none") {
   x.style.display = "block";
  } else {
  x.style.display = "none";
 }
}

Or you could just omit the ids and do it in a more dynamic way, like so:

$('body').on('click', '#add-el', () => {
  $('#container').append(`
  <div>
    <div>text</div>
    <button class="el-hider">Hide/Show</button>
  </div>`);
});

$('body').on('click', '.el-hider', ({target}) => {
  const element = $(target).parent().children()[0];
  
  if($(element).is(":visible")) {
    $(element).hide();
  } else {
    $(element).show();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add-el">Add element</button>
<div id="container">

</div>
MauriceNino
  • 6,214
  • 1
  • 23
  • 60