Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to add the <span> by javascript?
    text
    copied!<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/6689065/how-to-use-the-javascript-to-add-remove-the-css-colour-style-to-the-html-page">How to use the Javascript to add/remove the CSS/colour style to the html page?</a> </p> </blockquote> <p>I have a question on the HTML and javascript. I got the following paragrahe.</p> <pre><code>function add_span(){ // ?? } &lt;input type="button" onclick="add_span()" value="add span"/&gt; &lt;p&gt; statement1, statement2, statement3 &lt;/p&gt; </code></pre> <p>Is it possible to have the following result after the user</p> <ol> <li>select the highlighted text by mouse</li> <li>click the button</li> </ol> <p>e.g. </p> <ol> <li>highlight the 'statement1,'</li> <li>click the button</li> </ol> <p>Expected Result:</p> <pre><code>&lt;input tupe="button" onclick="add_span()" value"add span"/&gt; &lt;p&gt; &lt;span class="ABC"&gt;statement1,&lt;/span&gt; statement2, statement3 &lt;/p&gt; </code></pre> ##### Updated Code, but no work <pre><code>// updated code in the add_span var selectedText; if (window.getSelection) { selectedText = window.getSelection(); } else if (document.getSelection) // FireFox { selectedText = document.getSelection(); } else if (document.selection) // IE 6/7 { selectedText = document.selection.createRange().text; } //create the DOM object var newSpan = document.createElement('span'); // add the class to the 'spam' newSpan.setAttribute('class', 'ABC'); document.getElementById('text').appendChild(newSpan); var selectedTextNode = document.createTextNode(); newSpan.appendChild(selectedTextNode); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload