开发者

How to add the <span> by javascript? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to use the Javascript to add/remove the CSS/colour style to the html page?

I have a question on the HTML and javascript. I got the following paragrahe.

function add_span(){
     // ??
}

<input type="button" onclick="add_span()" value="add span"/>
<p> statement1, statement2, statement3 </p>

Is it possible to have the following result after the user

  1. select the highlighte开发者_Go百科d text by mouse
  2. click the button

e.g.

  1. highlight the 'statement1,'
  2. click the button

Expected Result:

<input tupe="button" onclick="add_span()" value"add span"/>
<p> <span class="ABC">statement1,</span> statement2, statement3 </p>
##### Updated Code, but no work
// 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);


You can get selected text from @Pezhvak IMV's answer:

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;
}

To add a element, you have to create a DOM node, set its attributes and add the element:

  1. Create a DOM node:

    var newSpan = document.createElement('span');

  2. Set the class

    newSpan.setAttribute('class', 'ABC');

  3. Add the span to under the <p> (The <p> should have a id or some mechanism of identifying it:

    <p id="text">

  4. Add the <span> to under the <p>

    document.getElementById('text').appendChild(newSpan);

  5. And set the text

    newSpan.innerHTML = selectedText;

You can also use createTextNode (alternative for step 5)

var selectedTextNode = document.createTextNode(); 
newSpan.appendChild(selectedTextNode);


To answer part of you question:

function getSelText() {
    var txt = '';
     if (window.getSelection)
    {
        txt = window.getSelection();
             }
    else if (document.getSelection) // FireFox
    {
        txt = document.getSelection();
            }
    else if (document.selection)  // IE 6/7
    {
        txt = document.selection.createRange().text;
            }
    else return; document.aform.selectedtext.value =  txt; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜