Avinash
Avinash

Reputation: 107

How to find div using id and data- with jquery

My html code looks like

<div id="1" data-level="level1">
<div id="replace"></div>
</div>
<div id="2" data-level="level1">
<div id="replace"></div>
</div>

I want to select div("replace") using jquery by id("1") and data-level("level1").

Upvotes: 2

Views: 140

Answers (4)

Milind Anantwar
Milind Anantwar

Reputation: 82241

You are having duplicate IDs in your code. IDs should be always unique. You can rather use same class and change markup to:

<div id="1" data-level="level1">
  <div class="replace"></div>
</div>
<div id="2" data-level="level1">
 <div class="replace"></div>
</div>

And then use attribute equals selctor along with find selector to find element by class:

$('#1[data-level="level1"] .replace')

Upvotes: 0

Yashpal Sindhav
Yashpal Sindhav

Reputation: 375

in this case you can do it with sibling or by next selector as per below code

$( "#1" ).siblings("replace");

or

$( "#1" ).next("replace");

Upvotes: 0

Rino Raj
Rino Raj

Reputation: 6264

Id must be unique. In your code id is repeating.

Use this

$('[id="1"][data-level="level1"] #replace')

OR

$('[id="1"][data-level="level1"]').find('#replace')

Upvotes: 1

Venkatesh K
Venkatesh K

Reputation: 66

This will select the required Div but if we are using id then there is no purpose of using data attribute also.

$("#1[data-level=level1]").find("#replace")

Upvotes: 0

Related Questions