1

I've got some simple html a bit like this

<a href="" data-type="" data-id="" data-tags="" id="" class="">balrbalr</a>

I'd like to be able to get the full contents of <a> as a string.

I know you can use .html to get the inner html, however if I use

var string = $('a').html();

If would return, balrblabrlabr

If I do string = $('a').parent.html();

I'd get ALL of the <a>'s inside the parent.

how would I go about just getting the full html content of itself?

Deduplicator
  • 43,322
  • 6
  • 62
  • 109
owenmelbz
  • 5,726
  • 15
  • 60
  • 109
  • See this question: http://stackoverflow.com/questions/2048720/get-all-attributes-from-a-html-element-with-javascript-jquery – xbonez May 19 '12 at 23:47

2 Answers2

5

You can use native javascript outerHTML property of DOM elements:

var string = $('a')[0].outerHTML;

Live DEMO

The outerHTML attribute of the element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can be set to replace the element with nodes parsed from the given string.

MDN


If you wish to get the outerHTML of multiple elements, you can use jQuery map function, like in this example:

var str = $('#foo a').map(function() {
    return this.outerHTML;
}).get();

Live DEMO

gdoron is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
0

Set your element's id to "a" and just use this function

    function msg() {
        var attrib="";
        var el =document.getElementById('a');
        for (var i = 0; i < el.attributes.length; i++) {
            attrib = attrib + ' ' + el.attributes.item(i).nodeName + ' = "' + el.attributes.item(i).nodeValue + '"';
        }
        alert(attrib);
    }
Krishanu Dey
  • 6,212
  • 6
  • 50
  • 67