Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get opening tag including attributes - outerHTML without innerHTML

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.

like image 659
Richard Kiefer Avatar asked Mar 07 '12 15:03

Richard Kiefer


People also ask

Is innerHTML a security risk?

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.

What does innerText do?

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.

What is outerHTML in Javascript?

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.

What does outerHTML return?

The outerHTML property sets or returns the HTML element, including attributes, start tag, and end tag.


1 Answers

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.

like image 146
Aaron Gillion Avatar answered Oct 02 '22 15:10

Aaron Gillion