0

I'm trying to get data from multiple divs sharing the same id using jquery, However every time I get just the first div data.

Code:

$(document).ready(function(){
    if($('[id="title"]').length > 0){
        console.log($('[id="title"]').html());
    }
});

<div id="title">Title one.</div>
<div id="title">Title two.</div>
<div id="title">Title three.</div>
<div id="title">Title four.</div>

The result that I get is: Title one.

I'm expecting to get: Title one. Title two. Title three. Title four.

Any solution would be very appreciated.

Ahmad Salameh
  • 121
  • 2
  • 13
  • Because ids are expected to be unique in a document by web standards. Use a class instead and stop trying to circumvent expected practices. – Taplar Jul 19 '18 at 16:44
  • Why don't you use classes? Or use a parent div with that id
    Title one.
    Title two.
    Check out this https://stackoverflow.com/questions/9233191/repeated-ids-in-an-html-document-how-bad-an-idea-is-it-if-they-are-scoped-by
    – jesusnoseq Jul 19 '18 at 16:44

1 Answers1

4

You cannot use same ID's on multiple div, Use class instead like .title

This will run through the amount of titles and return each text inside. Now I am using the for loop to do this, options like foreach exist.

$(document).ready(function(){

  /* How the Magic Works:
  var amount = $(".title").length;

  for (i = 0; i < amount; i++) {
    console.log($(".title").eq(i).text());
  }
  */

  // Can also be simplified to this thanks to Taplar
  $(".title").each(function(){
   console.log($(this).text());
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title">Title one</div>
<div class="title">Title two</div>
<div class="title">Title three</div>
<div class="title">Title four</div>
mustafa bagwala
  • 401
  • 5
  • 12
Luay
  • 789
  • 4
  • 15