joumvaer92 joumvaer92 - 2 years ago 92
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">

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


this is work.

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


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 Source

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>

Jquery code is same as you :-


It may help you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download