Search code examples
javascripthtmlhyperlinkhelper

How can I make text into links


I am working on a project and I need help with making any text into a link so, to sum up, what I need help with is I am creating a page where someone needs to attach a link to a word or more like how you can add links to words on google docs enter image description here


Solution

  • You could use link() method to add link to a text.

    // link() example
    var title = "Example";
    var url = "https://youtube.com";
    var result = title.link(url);
    document.getElementById("demo").innerHTML = result;
    
    // Form example
    document.getElementById("myBtn").addEventListener("click", displayLink);
    
    function displayLink() {
      let title = document.getElementById('title').value;
      let url = document.getElementById('url').value;
    
      // Write Javascript code!
      const appDiv = document.getElementById('app');
      appDiv.innerHTML = title.link(url);
    }
    <label>Example with link()</label>
    <div id="demo"></div>
    
    <br /><br />
    <label>Example With Form</label>
    <form>
      <input type="text" placeholder="Title" value="" id="title" />
      <input type="text" placeholder="Url" value="" id="url" />
    </form>
    <button id="myBtn">Add Link</button>
    <br /><br />
    <div id="app"></div>