jQuery: how to create a new div
, assign some attributes, and create an id from some other elements attributes?
How can I accomplish this. What I've tried below is not working and I'm unsure how to make it work.
What I'm trying to do is create a div
and assign it some attributes, then append this div
to all the < li > elements that are the on the last node of my unordered list. And lastly, but most important I want to retrieve the value of the attribute called "p_node" from the < li > that is being appended to and insert it in as part of the ID of the newly created div
.
Here's my current jQuery code:
$('<div />,{id:"'+ $("#nav li:not(:has(li))").attr("p_node").val() +'_p_cont_div", class:"property_position"}').appendTo("#nav li:not(:has(li))");
Here's the HTML before the div
creation:
<ul>
<li p_node="98" class="page_name">Category A</li>
</ul>
<ul>
<li p_node="99" class="page_name">Category B</li>
</ul>
Here's what I want it to look like after the new div
creation:
<ul>
<li p_node="98" class="page_name">Category A</li>
<div id="98_p_cont_div" class="property_position"></div>
</ul>
<ul>
<li p_node="99" class="page_name">Category B</li>
<div id="99_p_cont_div" class="property_position"></div>
</ul>
Update
This works:
$("#nav li:not(:has(li))").each(function () {
var self = $(this);
p_node = self.attr(\'p_node\');
self.after("<div class=\'property_position\' />");
});
This doesn't work:
$("#nav li:not(:has(li))").each(function () {
var self = $(this);
p_node = self.attr(\'p_node\');
self.after("<div id=\'" + p_node + "\' class=\'property_position\' />");
});
This also doesn't work:
$("#nav li:not(:has(li))").each(function () {
var self = $(this);
p_node = self.attr(\'p_node\');
self.after("<div class=\'property_position\' />");
$("li>div").attr("id",p_node);
});