简体   繁体   中英

How to wrap the newly input text into the following already-existed span tag

If user put something before wordx in contenteditable div, eg somthingwordx, since the newly added text "soemthing" was not wrapped into any existed span automatically, how do I know which span did user added text to and wrap it into that span using javascript?

Demo:

<div id="inputbox" style="border:1px solid lightgrey" contenteditable="true">
  <span id="1">word1</span>  <span id="2">word2</span>
  <span id="3">word3</span>  <span id="4">word4</span>  <span id="5">word5</span>  <span id="6">word6</span>  <span id="7">word7</span>  <span id="8">word8</span>  <span id="9">word9</span>  <span id="10">word10</span>  <span id="11">word11</span>  <span id="12">word12</span>
</div>

I have now updated the code with a solution for you that is working. Check out the snippet or the fiddle here: https://jsfiddle.net/4xcxLt34/2/

Hope it will help!

 $(document).ready(function(){ $('span').on('DOMSubtreeModified', function() { $('#result > p').text($(this).attr('id')); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="inputbox" style="border:1px solid lightgrey" contenteditable="true"> <span id="1"> word1</span> <span id="2"> word2</span> <span id="3"> word3</span> <span id="4"> word4</span> <span id="5"> word5</span> <span id="6"> word6</span> <span id="7"> word7</span> <span id="8"> word8</span> <span id="9"> word9</span> <span id="10"> word10</span> <span id="11"> word11</span> <span id="12"> word12</span> </div> <div id='result'> <h3> This is the span that is changed: </h3> <p> </p> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM