-1

I am trying to get the value of the id in html using jquery but not able to get that value

<div id="tar">...</div>
<div id="tar" class="helper">...</div>

the script is here

<script>
       console.log(($('#tar').html());
       console.log(($('#tar'));
   </script>

thank you in advance!

easypro
  • 1
  • 2

2 Answers2

0

You cant use the same id value twice . Id should be unique for each tag. Give a unique id or get the value via className. Please change it

Aniketh Saha
  • 843
  • 10
  • 22
0

The val() method is used to get the value attribute of the element. If you want to return the contents enclosed in the tag use the following:

 console.log(($('#tar').html())

If you are looking to get the value of a particular attribute such as the id you could use the following:

element.attr("id");

You also might want to make sure the id attributes you use are unique, otherwise change them to the class attribute. If you do this make sure you handle the selection of multiple elements though.

For example:

$('.tar').each(function(i, obj) {

    console.log((obj.html());

});
Tony
  • 2,890
  • 1
  • 24
  • 35
  • 1
    This answer ignores the duplicate id issue. – Taplar Apr 04 '18 at 17:05
  • The `tar` id is used twice .it should be unique . So may be this is the error – Aniketh Saha Apr 04 '18 at 17:06
  • @Taplar Ya you are right I added an explanation for that. – Tony Apr 04 '18 at 17:07
  • Ths OP clearly stated they want the ID, not the contents. Also, divs have no value attribute, only form elements do. – j08691 Apr 04 '18 at 17:08
  • @j08691 I find it a little strange that they would both want to select based on and return the `id`, so I am not 100% sure what they are looking for. I have included an example of how you could return the value of a particular attribute however. – Tony Apr 04 '18 at 17:15