0

Thought this was easy with Javascript. I was wrong: I have this HTML code (in the tinymce iframe body):

   <ul>
      <li><a href="#">First</a></li>
      <li><a href="#">Second</a></li>
      <li><a href="#">Third</a></li>
   </ul>

By putting the caret(cursor) somewhere on "Second" word and click a button I want to trigger an onclick-function that inserts a new "LI" AFTER the "Second" list point, resulting in this:

   <ul>
      <li><a href="#">First</a></li>
      <li><a href="#">Second</a></li>
      <li><a href="#">New inserted list item</a></li>
      <li><a href="#">Third</a></li>
   </ul>

Note that I don't have an ID or a class applied to the LI-tags. So I cant use getElementByID, and thats where my head dissimilates. (this is all going on inside a TinyMCE editor textarea, but that should not matter in general.)

Recoil
  • 481
  • 5
  • 11
  • You should encode the tags in the textarea. – epascarello Nov 25 '13 at 05:07
  • Matching a text version of HTML is not going to happen http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – epascarello Nov 25 '13 at 05:11
  • This is just an extraction of the main problem. The textarea-tag is not really part of the real code as this is inside an ifram of tinymce. I just focused here on getteing that Javascript that can insert that listitem after that Second-item. – Recoil Nov 25 '13 at 05:29
  • @epascarello Ouch, so Javascript can't select the LI-tag surrounding the cursor/caret position? Javascript can only select elements by ID? Really? – Recoil Nov 25 '13 at 05:45
  • Bascially it is a combination of http://stackoverflow.com/questions/3972014/get-caret-position-in-contenteditable-div and inserting a new element. – epascarello Nov 25 '13 at 05:54
  • This does what I want (http://jsfiddle.net/wygKS/), but uses getElementById. Is there another way to get to that LI-element when i have the caret inside it? I can get to it using getNode, parentNode, but can't insert after its closing tag. – Recoil Nov 25 '13 at 05:59

1 Answers1

1

Live demo here (click).

var anchors = document.querySelectorAll('ul li a');
console.log(anchors);

for (var i=0; i<anchors.length; ++i) {
  anchors[i].addEventListener('click', addList);
}

function addList(e) {
  var li = document.createElement('li');
  var a = document.createElement('a');
  a.href = '#';
  a.textContent = 'new item';
  a.addEventListener('click', addList);
  li.appendChild(a);
  e.target.parentNode.insertBefore(li, e.target.nextSibling);
}
epascarello
  • 204,599
  • 20
  • 195
  • 236
m59
  • 43,214
  • 14
  • 119
  • 136
  • sigh. I don't think that was there earlier. Maybe I missed it. @epascarello – m59 Nov 25 '13 at 05:05
  • @epascarello yeah, for sure. I copied the code right out his example. That kind of sucks to get a downvote for :) – m59 Nov 25 '13 at 05:07