1

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?

Quan
  • 27
  • 2
  • 6
  • You have to append it to the DOM at one point. Also you can set the `href` using [setAttribute](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute) or just the property `urlanchor.href = ""`. – Lain Aug 02 '20 at 08:18
  • Does this answer your question? [How do I create a link using javascript?](https://stackoverflow.com/questions/4772774/how-do-i-create-a-link-using-javascript) – Lain Aug 02 '20 at 08:21

1 Answers1

1

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.

cespon
  • 5,630
  • 7
  • 33
  • 47