Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript element html without children [closed]

In my javascript code I need to get the definition of an element, but without its content - neither text nor children.

E.g. for:

<div id="my_example_id" class="ShinyClass">
   My important text
   <span> Here</span>
</div>

I would like to write a javascript fucntion that when provided with the element of the div above will return the following as string:

<div id="my_example_id" class="ShinyClass">

I have been trying with different manipulations over the elements, functions like innerHTML, outerHTML and similar, but I was unable to figure out how to fetch only the part I am interested in. Is substring until the first > the best possible solution?

EDIT: selecting the element is not part of the question - I know how to do that, no prob. Rather the question is: when I have already selected a particular element how to parse as string only its own definition.

like image 968
Boris Strandjev Avatar asked Dec 24 '22 04:12

Boris Strandjev


2 Answers

UPDATE:

const div = document.getElementById('my_example_id'); // get the node
const html = div.outerHTML.replace(div.innerHTML || '', ''); // simple set logic

console.log(html);

Just some way to do this, not saying the best.

const div = document.getElementById('my_example_id');
const copy = div.cloneNode(true);
const parent = document.createElement('div');
copy.innerHTML = '';
parent.appendChild(copy); // I forgot to add this line.
const html = parent.innerHTML;

console.log(html);

Basically you create a copy of the div, create a parent, then remove innerHTML of the copied node to leave out just the 'div' itself. Append the copied node to the new parent and show the parent's innerHTML which is just the 'div' you wanted.

like image 74
Azamantes Avatar answered Jan 10 '23 13:01

Azamantes


you don't need to do all that fancy stuff copying it to a parent..

// make a copy of the element
var clone = document.getElementById('my_example_id').cloneNode(true);
// empty all the contents of the copy
clone.innerHTML = "";
// get the outer html of the copy
var definition = clone.outerHTML;

console.log(definition);

I threw it in a function in this fiddle: https://jsfiddle.net/vtgx3790/1/

like image 39
I wrestled a bear once. Avatar answered Jan 10 '23 11:01

I wrestled a bear once.