S
SM
Hello,
I have an unordered list similar to this one:
<ul id=list>
<li onclick="addParagraph(0)">Item 1</li>
<li onclick="addParagraph(1)">Item 2</li>
<li onclick="addParagraph(2)">Item 3</li>
</ul>
When I click on a item, a paragraph is inserted after that item. That
part works fine. Check code below.
Im having a probem when i click on the same list item again. It keeps
adding the paragraph over and over again.
I don't know how to control it. I figure that i problably need some
sort of toggle function
Also, when i click on another list item, i want the previous list item
paragraph to go way! and the new one to appear
How can this be done with Javascript and DOM?
Need help.
Thanks
MArco
//function that adds a <p> after a list item
function addParagraph(index) {
var list = document.getElementById('list');
var div = document.createElement('div');
div.className = 'lyrics';
var p = document.createElement('p');
var pTxt1 = document.createTextNode('Hello');
p.appendChild(pTxt1);
div.appendChild(p);
list.insertBefore(div, list.getElementsByTagName("li")[index + 1]);
}
<style type="text/css">
.lyrics { width:300px; border:1px solid blue; }
</style>
I have an unordered list similar to this one:
<ul id=list>
<li onclick="addParagraph(0)">Item 1</li>
<li onclick="addParagraph(1)">Item 2</li>
<li onclick="addParagraph(2)">Item 3</li>
</ul>
When I click on a item, a paragraph is inserted after that item. That
part works fine. Check code below.
Im having a probem when i click on the same list item again. It keeps
adding the paragraph over and over again.
I don't know how to control it. I figure that i problably need some
sort of toggle function
Also, when i click on another list item, i want the previous list item
paragraph to go way! and the new one to appear
How can this be done with Javascript and DOM?
Need help.
Thanks
MArco
//function that adds a <p> after a list item
function addParagraph(index) {
var list = document.getElementById('list');
var div = document.createElement('div');
div.className = 'lyrics';
var p = document.createElement('p');
var pTxt1 = document.createTextNode('Hello');
p.appendChild(pTxt1);
div.appendChild(p);
list.insertBefore(div, list.getElementsByTagName("li")[index + 1]);
}
<style type="text/css">
.lyrics { width:300px; border:1px solid blue; }
</style>