开发者

xml() function in jQuery

开发者 https://www.devze.com 2023-02-13 19:28 出处:网络
There is already the html() function in jQuery. The problem I am having with this function is that, in its returned html string,all the self-closing / are stripped off from the elements. For example,

There is already the html() function in jQuery.

The problem I am having with this function is that, in its returned html string, all the self-closing / are stripped off from the elements. For example,

<div>
<input type="text" name="textbox1" value="" />
</div>

Becomes:

<div>
<input type="text" name="textbox1" value="">
</div>

I know this is normal for this function since this is valid in html.

But I would like to have a function that returns valid xml so that the / is still there in the returned string.

It seems jQuery itself does not provide such a function, so I wonder if开发者_运维技巧 anyone knows of any plugin that can make this possible.

Thanks in advance.


I think you are misconceiving how browsers interpret HTML. They don't keep a copy of your source file and modify it according to your Javascript. Rather, a browser reads your HTML and parses it into a DOM representation. This corrects any mistakes you may have made in your HTML. When you try to get the HTML of an element, the element is converted to a string according to the current DOCTYPE. Since you probably have an HTML doctype (it's quite hard to get a browser to genuinely treat your document as XHTML), you get HTML returned to you.

Doing this in Javascript is almost certainly not the way to go.


I think this is what I need.

Thank you very much for everyone's reply.

http://code.google.com/p/jquery-clean/

UPDATE 1: I thought this plugin would work but actually it does not. The way I use it is that, I pass it the html string returned by html() and let it fix the tags which do not properly self-close.

However, the way it corrects the tags is not what I need (seems like a bug).

For example, passing it the following html:

<div><input type="text" id="txt1" name="txt1"><label for="txt1">TextBox1</label></div>

It gives:

<div><input type="text" id="txt1" name="txt1"><label for="txt1">TextBox1</label></input></div>

Rather than:

<div><input type="text" id="txt1" name="txt1" /><label for="txt1">TextBox1</label></div>

UPDATE 2: The bug I mention above is already fixed. This plugin works now. If you want to test it out, feel free to paste your html in this page and see if it works for you: http://www.antix.co.uk/Content/Demos/jQuery-htmlClean/Test.htm


You could try using the native .innerHTML property (you cen get the native element using .get() in jQuery).

0

精彩评论

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