-2

I have contenteditable div in HTML5. I have a ul li inside the DOM. When I click on that button I want that cursor placed inside the li using javascript. How can I do that?

<span class="mT2 mL10 bullotIcon fR vam" onclick="iconClick(this)">clickButton</span>
<div id="editableEvent" class="w100p  ht70 f13 textField w250 boxSizeBB whiteBg selev grayBdr oA" contenteditable="true" style="height: 100px;">
  <ul>
    <li>dafdsasdsdfasdfd</li>
    <li>dfsfsdfdsfsdfdfdsfsdfsdfdsf</li>
    <li>sdfsdfsdfsdfsdfdfsdffdf</li>
  </ul>
</div>
function iconClick(obj){
  if ($('#editableEvent').getSelection) {
     console.log($('#editableEvent').getSelection().anchorNode.parentNode);
  }
}

Normally my cursor was inside the content editable div. on click button i want the cursor placed element like 'li' Thanks in advance

Vijaykarthik
  • 333
  • 4
  • 10
  • 25

5 Answers5

0

Add code below after you click button.

 document.getElementById("editableEvent ul li").style.cursor = "default";
0

To remove an LI that was clicked on, you can use an event's target property to work out what you clicked on then remove it.

Plain JS:

document.getElementById('editableEvent').onclick = function(e){
  if(e.target instanceof HTMLLIElement){
    e.target.remove();
  }
}

jQuery:

$('#editableEvent').click(function(e){
  $target = $(e.target);
  if($target.is('li')){
    $target.remove();
  }
});
meltuhamy
  • 3,293
  • 4
  • 23
  • 22
0

I am just providing links that may help you

https://stackoverflow.com/a/3976125/3979414 - to find the current position in contentEditable text.

https://stackoverflow.com/a/1211981/3979414 - to find the cursor mentioned tag

https://stackoverflow.com/a/4232971/3979414 - to remove the corresponding tag

Community
  • 1
  • 1
Kumar
  • 108
  • 1
  • 12
0

you can also try:

 $('li').on('click',function(){

        $(this).remove();
    });
Aman Nagarkoti
  • 198
  • 1
  • 12
  • This won't work for dynamically created `
  • `s, for instance, if the `li` is added using the contenteditable by copying and pasting it.
  • – meltuhamy Sep 22 '16 at 12:51
  • yes correct, for that issue use $('body').on('click', 'li', function(){}); – Aman Nagarkoti Sep 22 '16 at 12:54
  • and inside function write $(this).remove(); – Aman Nagarkoti Sep 22 '16 at 12:55
  • or, better, listen for click events on the `#editableEvent` instead of body as it is not the body's concern – meltuhamy Sep 22 '16 at 12:55
  • yes if the div is static then we can use #editableEvent in place of body. I am giving just a generic solution. – Aman Nagarkoti Sep 22 '16 at 13:02