> On May 21, 4:16 am, SM <servandomont
@gmail.com> wrote:
> > 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]);
> Inserting a div into a ul element creates invalid HTML. No doubt
> browsers are using error correction to do something with it, but to
> get consistent results you must enter the div as a child of the li
> element, not the ul.
> In any case, the div doesn't seem to do anything other than wrap the p
> element, so why not just insert that?
> I also would not expect list.getElementsByTagName("li")[index + 1] to
> work always as it create a reference to a non-existent element. If
> that was required (say you are inserting an li after another one) you
> should use nextSibling:
> var newLi = document.createElement('li');
> var li = list.getElementsByTagName("li")[index];
> ul.insertBefore(newLi, li.nextSibling);
> But that isn't needed in this case since you aren't inserting into the
> UL, you should be inserting into the LI, so try something like:
> var ul = document.getElementById('list');
> var li = ul.getElementsByTagName('li')[index];
> var p = document.createElement('p');
> var pTxt1 = document.createTextNode('Hello');
> li.appendChild.(p);
> --
> Rob
Thanks guys,