Search code examples
javascripthtmldomhyperlinkhref

JavaScript, HTML, no JQuery - how to add a string that contains a link in the middle of a sentence?


I am fairly new to JavaScript. I'm trying to add a paragraph to a HTML (preferably using DOM). A paragraph should contain a string, a sentence, that has a link in the middle. A paragraph will have different contents depending on a user choice and will display on a webpage after clicking a button. Part of my code that is related to the question pasted below. Where a link will be 'contactThem'.

//Returns a correct text to be displayed in a hidden panel.
function displayText(result) {
    const fR = parseInt(result);
    const contactThem = "<a href='form.html'>form</a>";
    let toInclude = "";
    if (fR < 5) {
        toInclude = "Some text";
    } else {
        toInclude = "Different text" + contactThem + "more text.";
    }
    return toInclude;
}

//Displays hidden panel with contents
function showPanel(displayText) {
    const toShow = displayText;
    const square = document.getElementById("toBeDisplayed");
    while (square.hasChildNodes()) {
        square.removeChild(square.lastChild);
    }
    const yourM = document.createElement("h2");
    let yourMT = document.createTextNode("Title");
    const pp = document.createElement("p");
    let ppT = document.createTextNode(toShow);
    yourM.appendChild(yourMT);
    square.appendChild(yourM);
    pp.appendChild(ppT);
    square.appendChild(pp);
    square.style.visibility = "visible";
}

I suspect that my approach might be wrong... I was thinking about maybe creating 2 separate divs and displaying them depending on users choice, but I really would rather do it in JavaScript if possible. I do understand that adding links as variables is incorrect. It is a temporary holder until I have a solution.


Solution

  • Whenever you want to add an HTML Element, such as <a href="http://my_url.com"> inside an existing element, you can do so with HTMLElement.innerHTML = "text that will be rendered" (as opposed to HTMLElement.innerText, which will render everything as is).

    In your case, it would be something like:

    const contactThem = "<a href='form.html'>form</a>";
    let el = document.createElement("p")
    el.innerHTML = "Different text" + contactThem + "other text."