joumvaer92 joumvaer92 - 6 months ago 11
Javascript Question

Hide an element using a specific id

I have this html structure:

<div id="main">
<div id="box" data-id="1">
<div id="box" data-id="2">
<div id="box" data-id="3">
<div id="box" data-id="4">
</div>


When I've a click event in jquery on a button I want that the box with data-id="1" become hidden:

$('#box[data-id=1]').hide();


this is work.

However if I want that the data-id="2" become hidden:

$('#box[data-id=2]').hide();


this doesn't works and I should write like:

$('#main #box[data-id=2]').hide();


why should the last one work or the one before shouldn't?

Answer

You can use id unique in page and you made mistake there you have define more then one box id to that div so change your html code as following :-

<div id="main">
  <div class="box" data-id="1">1</div>
  <div class="box" data-id="2">2</div>
  <div class="box" data-id="3">3</div>
  <div class="box" data-id="4">4</div>
</div>

Jquery code is same as you :-

$('.box[data-id=2]').hide();

It may help you.