0

i am writing some JavaScript code and i test the code in console or via an alert msg i get the following text as return value.

if i use this code:

     alert($("#images img"));     

i get:

   [object object]

how can i get the name of the tag, ie, if its an image tag or li so i know it is being targeted correctly.

i use firefox and chrome..is there a way i can locate this under the developer tools or firebug...if so then under which section?

user3262344
  • 125
  • 2
  • 4
  • 12
  • 4
    [Learn how to](http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820) [properly **debug** JavaScript](https://developers.google.com/chrome-developer-tools/docs/javascript-debugging). – Felix Kling Mar 15 '14 at 04:33

3 Answers3

2

Avoid alert for debugging as it only outputs strings, use the console:

console.log($("#images img")[0].tagName)

You can access the DOM element of any jQuery collection with bracket syntax, like an array.

If you use alert(obj) you get [object Object] which is an object's toString output, as alert will coerce anything into a string. If you use console.log(obj) you'll see the object as a real object.

elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • Amusing. You tell them to use the console to look at more than just strings and then you recommend they log a string `$("#images img")[0].tagName`. – jfriend00 Mar 15 '14 at 05:06
  • OP will figure out how to log the object if needed, the fact still remains, use console, not alert. – elclanrs Mar 15 '14 at 05:10
  • I don't disagree with using `console.log()` (actually I generally find it more useful to use the debugger), but I just thought your answer was strangely worded which you could fix by explaining what the OP would see if they used `console.log()` on an object. – jfriend00 Mar 15 '14 at 05:13
1

For get the tag name you can use prop() method.

$("#images img").prop("tagName");

For put the script into debugger you can use the console tab on Chrome,

How to get the console tab on chrome?

Use the keyboard shortcut Command - Option - J (Mac) or Control -Shift -J (Windows/Linux).

Select View > Developer > JavaScript Console.

More information about Console Tab

Suman Bogati
  • 6,289
  • 1
  • 23
  • 34
0

If you want more information about the tag you can do something like this:

console.log($("#images img")[0].outerHTML)

Or if you might have more than one item:

$("#images img").each(function(){
    console.log(this.outerHTML);
});

Which will print the below to the Firebug/Chrome console:

<img src="https://www.gravatar.com/avatar/5e188e06ccdee56a568db3c383fa0f3d?s=24&amp;d=identicon&amp;r=PG" alt="" class="avatar-me js-avatar-me" width="24" height="24">
row1
  • 5,568
  • 3
  • 46
  • 72