beseder
beseder

Reputation: 1372

jQuery: Select outer tag

Given the following xml:

<svg height="10" width=20">
  <g>
    ...
  </g>
  ...
</svg>

How can I get only the outer element ? It would be just outerHTML without innerHTML.

Upvotes: 0

Views: 69

Answers (3)

Jai
Jai

Reputation: 74738

It would be just outerHTML without innerHTML.

use .clone() with .html() like this:

var cloned = $('svg').clone().html('');

Upvotes: 1

Gagan Gami
Gagan Gami

Reputation: 10251

No need to generate a function for it. Just do it like this:

For Example :

$('A').each(function(){
    var s = $(this).clone().wrap('<p>').parent().html();
    console.log(s);
});

(Your browser's console will show what is logged, by the way. Most of the latest browsers since around 2009 have this feature. On Firefox, you have to install Firebug.) The magic is this on the end:

.clone().wrap('<p>').parent().html();

The clone means you're not actually disturbing the DOM. Run it without it and you'll see P tags inserted before/after all hyperlinks (in this example), which is undesirable. So, yes, use .clone().

The way it works is that it takes each A tag, makes a clone of it in RAM, wraps with P tags, gets the parent of it (meaning the P tag), and then gets the innerHTML property of it.

via Volomike

Upvotes: 0

T J
T J

Reputation: 43156

You can use outerHTML

The outerHTML attribute of the element DOM interface gets the serialized HTML fragment describing the element including its descendants.

document.getElementsByTagName('svg')[0].outerHTML;

Upvotes: 0

Related Questions