0

Possible Duplicate:
How to getElementByClass instead of GetElementById with Javascript?
How to Get Element By Class in JavaScript?

I need to get the complete tag by class. Is it possible to do in javascript without any cross browser issues.

For eg., if the element is,

<img src="hello.jpg" class="myclass" />

Then i need to get,

<img src="hello.jpg" class="myclass" /> by using class name. Any solution or suggestion on this would be greatly appreciated.

Note: Please note that, i don't wnt to use any JavaScript library.

Community
  • 1
  • 1
Stranger
  • 10,332
  • 18
  • 78
  • 115
  • No I'm not using any JavaScript library. – Stranger Jul 22 '12 at 15:41
  • What operation do you plan to do after getting the whole element. – gideon Jul 22 '12 at 15:41
  • What is a "complete" element? There's dozens, hundreds, possibly thousands of questions asking this; have those not worked for you? – Jared Farrish Jul 22 '12 at 15:41
  • @JaredFarrish The element with the same class will not occur more thn once – Stranger Jul 22 '12 at 15:42
  • `document.getElementsByClassName("myclass")` should return a HTMLCollection you get an array of hte html elements -> `document.getElementsByClassName("myclass")[0]` would give you what you want – Moritz Roessler Jul 22 '12 at 15:43
  • @MarcB - Isn't `document.getElementsByClassName()` not supported in some earlier but somehow still "required" browsers? In that case, `document.querySelector()` would also be relevant. – Jared Farrish Jul 22 '12 at 15:43
  • Udhay, that is not per se a *class*; use an `id` and then `document.getElementById('id')`. Succinct and *correct*. `class` should only be used if one or more elements are being grouped, `id` for non-serial elements (and there should only be one `id` value per page). – Jared Farrish Jul 22 '12 at 15:44
  • http://forums.devshed.com/javascript-development-115/javascript-get-all-elements-of-class-abc-24349.html this will solve it – Frederik Prijck Jul 22 '12 at 15:45

1 Answers1

0

Find your element using document.getElementsByClassName('myclass'). This returns an array, so you can check if it's empty and retrieve its first element via [0].

After that, you can get the full tag as string using its outerHTML property.

Kos
  • 70,399
  • 25
  • 169
  • 233