Reputation: 51371
DOM
<div id="a">
<div id="b"></div>
<div>
<p>Insert me after #b</p>
Requirement is insert p tag after '#b', and when the insert operation happened again, only replace the p tag instead of adding more.
Thanks for your help
Upvotes: 0
Views: 1545
Reputation: 5131
You can use $.after()...
<div id="a">
<div id="b"></div>
<div>
...
<script>
$("#b").after("<p>Insert me after #b</p>");
</script>
Upvotes: 1
Reputation: 11215
This will insert it directly after #b, within #a, but if it already exists, then it wont insert it again.
$(document).ready(function(){
if ($('#newP').length == 0) {
$('#b').append('<p id="newP">Insert me after #b</p>')
}
});
Upvotes: 2
Reputation: 146
This function will remove an existing element then add a new element. If one does not exist it will simply add the element.
<body>
<script type="text/javascript">
$(document).ready(function() {
function addAfterB(pElement) {
if (!$('#b ~ p')) {
$(pElement).insertAfter('#b');
} else if ($('#b ~ p')) {
$('#b ~ p').remove();
$(pElement).insertAfter('#b')
}
}
addAfterB('<p>New Item 1</p>');
});
</script>
<div id="a">
<div id="b"></div>
<p>hello</p>
<div>
Upvotes: 1
Reputation: 82963
Try this:
function insertP(html)
{
var a = $("#a");
var p = a.find("p")
if(p.length == 0)
{
p = $("<p></p>").appendTo(a);
}
p.html(html)
}
Upvotes: 2