FunnyGirl
FunnyGirl

Reputation: 27

Select Specific ID using Jquery

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

Answers (4)

Ibrahim Khan
Ibrahim Khan

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

Walfrat
Walfrat

Reputation: 5353

I'll comment some design problem 1st :

  1. Unlike custom attributes id is a standard attributes that is supposed to be unique accross the page (see http://www.w3schools.com/tags/att_global_id.asp).
  2. to search for an id you can just search for #D61. see https://api.jquery.com/id-selector/

Now the answer : check this link : https://api.jquery.com/find/

So that'll give : $('#game1').find('#KD61');

Upvotes: 0

Mahesh
Mahesh

Reputation: 1081

var $reqElement = $("#game1").find("#D61");
reqElement.addClass('selected');

Upvotes: 0

Shashank
Shashank

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

Related Questions