开发者

JQuery: How to get all of a selector's html attributes in one statement, as a string?

开发者 https://www.devze.com 2022-12-21 02:33 出处:网络
I\'ve got a div that looks like this: <div id=\"examp开发者_StackOverflowleDiv\" class=\"class1 class2\" title=\"example title\"></div>

I've got a div that looks like this:

<div id="examp开发者_StackOverflowleDiv" class="class1 class2" title="example title"></div>

I've selected with JQuery using this statement:

var $div = $('#exampleDiv');

What I'd like to get is a string of the tag itself as html, so that I actually get:

"<div id='exampleDiv' class='class1'....", etc.

Does anyone know of a JQuery function I could use that does this, given the selector? I'm thinking something like $div.htmlHeader() or something like that.

Any help would be appreciated. Thanks.


Clone the element into a new div, remove the clone's children, and print the parent div's html:

var html = $("<div/>").append($("#exampleDiv").clone().empty()).html();

If the element you want to print has a lot of descendents and you don't want to incur the cost of cloning the entire hierarchy, and if you don't mind briefly leaving the safety of jQuery's DOM interface, you could do this instead:

var html = $("<div/>").append($("#exampleDiv")[0].cloneNode(false)).html();


Here you go:

$.fn.tagonly = function() {
    return $('<div/>').append($(this).clone().empty())
        .html().replace(/>(.|[\r\n])*$/ig, '>');
};

Edit Fixed the extra ) and the newline issue. Thanks patrick.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号