Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For future Googlers, there is a way to do this without jQuery:

tag = elem.outerHTML.slice(0, elem.outerHTML.indexOf(elem.innerHTML));

Since outerHTML contains the opening tag followed by a mirror of what innerHTML contains, we can substring the outerHTML from 0 (the beginning of the opening tag) to where the innerHTML begins (end of opening tag), and since innerHTML is a mirror of outerHTML, except for the opening tag, only the opening tag will be left!

This one 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...