Adam Rackis
Adam Rackis

Reputation: 83376

Get element's html tag content

Is it possible to get a node's top-level tag html via the dom api? To be clear, if I have

<div data-x="a">
    <span>Hello</span>
</div>

I want to just get back <div data-x="a">

Is a crude string matching on outerHTML the best I can do, or is there a fast and direct way to achieve what I want?

Upvotes: 1

Views: 115

Answers (2)

Kyle Trauberman
Kyle Trauberman

Reputation: 25694

If you clone the node, the innerHTML property will be empty. For your example, a shallow clone is appropriate (pass false or don't pass anything).

// get the div element
var element = document.querySelectorAll('div')[0];

// view the outerHTML of the element
console.log('original outerHTML', element.outerHTML);

// clone the element
var clone = element.cloneNode();

// view the outerHTML of the clone
console.log('outerHTML of clone', clone.outerHTML); // has what you want
<div data-x="a">
    <span>Hello</span>
</div>

.cloneNode() on MDN

Upvotes: 3

David P
David P

Reputation: 2103

You can use the outerHTML to get all of it, and the innerHTML to get the stuff just inside. Then do a string replace on the outerHTML, replacing the innerHTML with an empty string, and doing the same for the end tag.

Upvotes: 1

Related Questions