Reputation: 27
I have a game board which is broken up into different section ex. game1, game2... I am trying to use jquery to add a class to a specific div with an ID. So in my PHP below:
<div id="game1" class="playarea">
<div id="K12" class="playnum" data-game="game1">12</div>
<div id="D61" class="playnum" data-game="game1">61</div>
<div id="N29" class="playnum" data-game="game1">29</div>
<div id="P06" class="playnum" data-game="game1">06</div>
<div id="X54" class="playnum" data-game="game1">54</div>
</div>
<div id="game2" class="playarea">
<div id="K12" class="playnum" data-game="game1">12</div>
<div id="D61" class="playnum" data-game="game1">61</div>
<div id="N29" class="playnum" data-game="game1">29</div>
<div id="P06" class="playnum" data-game="game1">06</div>
<div id="X54" class="playnum" data-game="game1">54</div>
</div>
I want to .addClass to the div with ID "D61" ONLY from the DIV with ID "game1". This function will be performed from a button so there is no context like "this". I have been trying .children() and even .find() or .attr() but no luck.
Right now I am using
$('[id="D61"]').addClass("selected");
But the problem is that it will .addClass() to both DIVs in game1 and in game2. How can I better narrow this down?
Upvotes: 0
Views: 89
Reputation: 20740
You can do it like following.
$('#game1 #D61').addClass('selected').
You are duplicating id
. id
should be unique. You can use class D61
instead of id
like following.
<div class="D61 playnum" data-game="game1">61</div>
And then the js
will be like this.
$('#game1 .D61').addClass('selected').
Upvotes: 2
Reputation: 5353
I'll comment some design problem 1st :
Now the answer : check this link : https://api.jquery.com/find/
So that'll give : $('#game1').find('#KD61');
Upvotes: 0
Reputation: 1081
var $reqElement = $("#game1").find("#D61");
reqElement.addClass('selected');
Upvotes: 0
Reputation: 2060
It can be done using the code below:
$('#game1 > #D61').addClass("selected");
The div with id="game"
is the parent with its immediate children with id="D61"
, so it will target only the div with id="game1".
Upvotes: 0