jQuery DOM-add, remove nodes
There is no way to implement such a task: when you click on $("div.block")
, a new element <div></div>
should appear immediately after it; when you click on the second one, the same element is deleted.
Up to
...
<header></header>
<div id="content">
<div class="logoblock"></div>
<div class="block"></div>
<div class="block"></div>
</div>
<footer></footer>
...
After
...
<header></header>
<div id="content">
<div class="logoblock"></div>
<div class="block"></div> // кликаем
<div></div> // добавляем
<div class="block"></div>
</div>
<footer></footer>
...
I understand, of course, that toggle(click1,click2);
works here, but I can't figure out how to add an element; more precisely, I can't figure out how to get to the element from which it can be added.
0
Author: Nicolas Chabanovsky, 2011-07-20
2 answers
Everything is done simply. There is such a function .insertAfter()
to insert an element after the specified one, and the function .insertBefore()
to insert up to the specified element.
$(function () {
$('div.block').click(function () {
$('<div>').text('my text').insertAfter(this);
});
});
3
Author: GLAGOLA, 2011-07-20 21:13:18
I see the solution like this (the colors are set for clarity):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Добавление элемента</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#razhdel').click(function(){
$(this).append('<div id="new">New</div').css('border', '1px solid blue');
$('#new').css('background', 'blue');
});
});
</script>
<style type="text/css">
#razhdel {
background: red;
width: 300px;`
}
</style>
</head>
<body>
<div id="razhdel">
bla-bla
</div>
</body>
</html>
0
Author: LeD4eG, 2011-07-21 15:52:19