Search code examples
javascriptswap

Change span to unknown on click in javascript


I have a span element in html that I want to replace with whatever text a user puts in the textbox on click. This is how far I've come, but I only seem to be able to change the text to what I put in the code.

function swap_text() {
    let input_text = document.getElementById("input_text").value;
    let text_element = document.getElementById("text");
    let all_spans = text_element.getElementsByTagName("span");
    for (let span of all_spans) {
        span.innerText = span.textContent = ("text value to assign");
    }
     console.log(input_text);
}

Solution

  • I tried to answer your question but it was hard without having the html.

    you can get the input value like you did and then iterate through the spans elements (or get just the one you need by id for example) and change the text content.

    function swap_text() {
        let input_text = document.getElementById("input_text").value;
        let all_spans = document.getElementsByTagName("span");
        for (let span of all_spans) {
             span.textContent = input_text;
        }
         console.log(input_text);
    }
    <span>my span</span>
    <input type="text" id="input_text">
    <button onclick="swap_text()">swap</button>