Denis Sorokin
Denis Sorokin

Reputation: 35

Find the same divs in DOM tree

I have a DOM tree:

<div id="all">
  <div id="second">
    <div id="target"></div> *
    <div id="somediv"></div>
  </div>
  <div id="second">
    <div id="target"></div>
    <div id="somediv"></div>
  </div>
  <div id="second">
    <div id="target"></div>
    <div id="somediv"></div>
  </div>
</div>

How I can get all divs with id="target"?

$('#second').siblings().andSelf().children(':first') - shows only the first target (*), ignoring the rest.

Upvotes: 1

Views: 124

Answers (3)

Dipak
Dipak

Reputation: 12190

You can not repeat ID in HTML.. replace id="target" with class="target" and then -

$('#all').find('.target');

Upvotes: 1

Ben Clayton
Ben Clayton

Reputation: 82219

You can't have multiple divs with the same ID in an HTML document. Instead, use class="target". Then you can get all divs with the class target in all with

$("#all .target")

Upvotes: 5

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41767

Try the following:

$('div[id=second]').siblings().andSelf().children(':first')

When presented with an id selector, jQuery will only return the first element with that id. This is because having elements with the same id is invalid HTML. HTML parsers are generally flexible and will probably display fine in most browsers, however this is not guaranteed to be the case. Consider changing your markup to use data- attributes or CSS classes or similar rather than IDs.

Upvotes: 1

Related Questions