I would like to retrieve a certain tag element with its attributes from the DOM. For example, from
<a href="#" class="class">
link text
</a>
I want to get <a href="#" class="class">
, optionally with a closing </a>
, either as a string or some other object.
In my opinion, this would be similar to retrieving the .outerHTML
without the .innerHTML
.
Finally, I need this to wrap some other elements via jQuery. I tried
var elem = $('#some-element').get(0);
$('#some-other-element').wrap(elem);
but .get()
returns the DOM element including its content. Also
var elem = $('#some-element').get(0);
$('#some-other-element').wrap(elem.tagName).parent().attr(elem.attributes);
fails as elem.attributes
returns a NamedNodeMap
which does not work with jQuery's attr()
and I was not able to convert it.
Admitted that the above examples are not very senseful as they copy also the element's no-longer-unique ID. But is there any easy way? Thanks alot.
Setting the value of innerHTML lets you easily replace the existing contents of an element with new content. Note: This is a security risk if the string to be inserted might contain potentially malicious content.
The innerText property of the HTMLElement interface represents the rendered text content of a node and its descendants. As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard.
The outerHTML attribute of the Element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can also be set to replace the element with nodes parsed from the given string.
The outerHTML property sets or returns the HTML element, including attributes, start tag, and end tag.
There is a way to do this without jQuery.
This also works with <br>
tags, <meta>
tags, and other empty tags:
tag = elem.innerHTML ? elem.outerHTML.slice(0,elem.outerHTML.indexOf(elem.innerHTML)) : elem.outerHTML;
Because innerHTML would be empty in self-closing tags, and indexOf('')
always returns 0, the above modification checks for the presence of innerHTML
first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With