0

If I have two DOM element like this:

<img id="test1" src="xyz" />

<a id="test2" href="#">Test 2</a>

And I'm selecting them in jQuery like this:

$('#test1') and $('#test2')

I want to be able to return img and a respectively. Using either vanilla Javascript or jQuery, what's the best way to do this?

JVG
  • 20,198
  • 47
  • 132
  • 210

1 Answers1

5

You'll need to get a reference to the DOM element and use the native nodeName property.

You can do this with jQuery: $('#test1').prop('nodeName').toLowerCase()

Or with vanilla js: document.getElementById('test1').nodeName.toLowerCase()

cfs
  • 10,610
  • 3
  • 30
  • 43
  • 4
    Given the question, it might be worth throwing a `toLowerCase()` in there as well (though I don't know if that's a specific request). – David Thomas Jun 19 '13 at 13:41
  • @DavidThomas good suggestion, I actually didn't consider that myself and you probably just saved me a good hour or two of future debugging! Upvotes for you. – JVG Jun 19 '13 at 13:42
  • 2
    Stick with `nodeName`: http://stackoverflow.com/questions/4878484/difference-between-tagname-and-nodename . And instead of `.get(0).tagName`, you could use `.prop("tagName")` (or `nodeName`) – Ian Jun 19 '13 at 13:45
  • @Ian I didn't know about `nodeName`; thanks! – cfs Jun 19 '13 at 13:46