jQuery .html() Function
The following code creates li from div's but the divs still appear in the source, what have I missed?:
$(document).ready(function(){
var makeLI = $("div").html("<li class='blue'>" +
"Here is a new <li > element.</li>");
$("body").append("<ul>");
$("ul").append(makeLI);
});
A publication states:
Navigate to the file in your browser. The elements are converted to elements with the text we want displayed.
However in FF 6 the div's remain:
<div><li class="blue">Here is a new <li > element.</li></div>
------------------Complete Code------------------
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<ti开发者_高级运维tle>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
.blue { color:blue; }
</style>
</head>
<body>
<h1>Rewriting three <div> elements</h1>
<div></div>
<div></div>
<div></div>
</body>
</html>
$(document).ready(function(){
var makeLI = $("div").html("<li class='blue'>" +
"Here is a new <li > element.</li>");
$("body").append("<ul>");
$("ul").append(makeLI);
});
makeLI
is the div
element. The li
is a child of it. Of course if you append the div
somewhere it will be there. If you only want to append the li
element, you have to call children
:
$("ul").append(makeLI.children());
Or simply omit the div
:
$('body').append($("<ul />").append("<li class='blue'>" +
"Here is a new <li > element.</li>"));
Btw. the div
will be there in all browsers. You might not see it, because browsers tend to correct invalid HTML. A div
element inside a ul
element is not valid and it will probably be moved after the ul
. Nevertheless, you should create valid HTML.
You are creating that div in the $("div") skip that and you should be set
var $li = $("<li>");
$li.html("Here is a new <li > element.");
$li.addClass('blue');
精彩评论