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
  • 44,692
  • 7
  • 66
  • 118
owenmelbz
  • 6,180
  • 16
  • 63
  • 113
  • See this question: http://stackoverflow.com/questions/2048720/get-all-attributes-from-a-html-element-with-javascript-jquery – Ayush 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
  • 147,333
  • 58
  • 291
  • 367
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,326
  • 7
  • 51
  • 69
  • @VisioN. [It works](http://jsfiddle.net/GZXpV/5/), but in a very unefficient way. – gdoron May 20 '12 at 00:26
  • Now i'm using a veriable `el` rather than using `document.getElementById('a')` multiple times. – Krishanu Dey May 20 '12 at 00:32
  • @gdoron Mmm... I have another approach http://jsfiddle.net/GZXpV/6/. Maybe it is not so flexible... Should I add it as an answer? – VisioN May 20 '12 at 00:34
  • @VisioN. Hell no! You regex the whole body!!! do you know how risky and inefficient it is? – gdoron May 20 '12 at 00:38
  • @KrishanuDey You can better assign `document.getElementById('a').attributes` to a variable. – VisioN May 20 '12 at 00:39
  • @gdoron Yeah! I can invent several more "wonderful" solutions ;) – VisioN May 20 '12 at 00:40
  • @VisioN :it works. but will you explain how? what does this expression mean, `/()/.exec(body);` ? – Krishanu Dey May 20 '12 at 00:40
  • @KrishanuDey. it's a regular expression looking for an anchor with the `a` id. – gdoron May 20 '12 at 00:41
  • @KrishanuDey This expression shows almost the same approach as you presented in your answer. It should not be used for such an easy task. `outerHTML` does the job. Nothing else needed. – VisioN May 20 '12 at 00:42