Using custom xml elements with JQuery
Given the following:
<p>This is a <fund id="12345">Test Fund</fund>. More text.</p>
How do I extract the text ("Test Fund") from the fund element?
I have tried the following:
$('fund').each(function(index) {
alert($(this).text());
});
I can retrieve the id attribute as follows:
alert($(this).attr("id"));
I have had no luck with text() html() etc.
EDIT: Initially I had only tried IE8, But after test in firefox I discover it works with FF just fine. I then reviewed in IE dev tools and noticed that the Dom explorer was treating the opening tag as a stand-alone node, as well as doing this to the remaining text, and closing tag.
I found some info on using a custom name开发者_开发技巧space as follows:
<html xmlns:myns>
<head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// Your code here
$('myns:fund').each(function(index) {
alert(index + ': ' + $(this).attr("id"));
});
});
</script>
</head>
<body>
<p>Sample paragraph.</p>
<p>This is a <myns:fund id="12345">Test Fund</fund>. More text.</p>
</body>
</html>
This fails also but renders correctly in the IE DOM explorer.
Your code works fine for me in Firefox 3.6 when I add the missing curly brace before the last parenthesis:
$('fund').each(function(index) {
alert($(this).text());
});
The above correctly prints Test Fund
.
EDIT: I got it working in Internet Explorer 8 by calling html() on the <p>
element, applying $() to the result and calling text() on that:
$(document).ready(function(index) {
alert($($("p").html()).text());
});
Try grabbing the contents of the <p>
tag as an HTML string, and passing that to the jQuery constructor, rather than trying to get the fund tag direct from the page:
var html = $("p").html();
alert($("<div>" + html + "</div>").find("fund").text());
Edit: you need to wrap the html inside a div (or other) element so jQuery doesn't get confused and think it's a selector. Works here: http://jsfiddle.net/uRggd/1/
精彩评论