Quan
Quan

Reputation: 27

Nothing changed when I try to insert an html element using JavaScript

I'm creating a simple text editor in html and I have a function which allow user to insert website link into a text. Here is the code:

    function setUrl() {
        window.url = document.getElementById('txtFormatUrl').value;
        window.sText = document.getSelection();
        var urlanchor = document.createElement("A");
        var urlatt = document.createAttribute("href");
        urlatt.value = window.url;
        urlanchor.setAttributeNode(urlatt);
        window.sText = urlanchor;
    }

How it works is that there will be a place to edit text and a box to enter URL. The user first highlighted the text then enter the URL, after that. The user presses the insert button which will called the setUrl() function. But when I try, the URL didn't get inserted into the text, when open the F12 console, I saw that the element don't get insert. So what's wrong with my code?

Upvotes: 1

Views: 176

Answers (1)

cespon
cespon

Reputation: 5760

Supposing that the element with ID txtFormatUrl is an <input> with a valid URL, the code is the following:

function setUrl() {
    var url = document.getElementById('txtFormatUrl').value; // Get value from input tag
    var selection = document.getSelection(); // Get info from text selected

    if(selection.rangeCount) {
        var textSelected = selection.toString(); // Get text selected
        var element = document.createElement('a'); // Create a new anchor DOM node
        element.innerText = textSelected; // Set de text selected to the new anchor DOM node
        element.setAttribute('href', url); // Set a href value

        var range = selection.getRangeAt(0); // Get selection range
        range.deleteContents(); // Delete the current text
        range.insertNode(element); // Replace the text
    }
}

You can get more info here about replacing a selected text form another. Also, take a look at the DOM Range W3 specification or DOM Range MDN docs.

Upvotes: 1

Related Questions