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?

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

@KrishanuDey. Did you use a browser with a console? change console.log to alert
@KrishanuDey. So.. why doesn't it work for you?! what happen when you change to alert?
Here is another screenshot when using alert(). freeimagehosting.net/newuploads/c4j4f.png
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);
    }

9 Comments

@VisioN. It works, but in a very unefficient way.
Now i'm using a veriable el rather than using document.getElementById('a') multiple times.
@gdoron Mmm... I have another approach jsfiddle.net/GZXpV/6. Maybe it is not so flexible... Should I add it as an answer?
@VisioN. Hell no! You regex the whole body!!! do you know how risky and inefficient it is?
@KrishanuDey You can better assign document.getElementById('a').attributes to a variable.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.