Home > database >  Swap text so that it replaces a string with user inputs and loop through a textand replace the conte
Swap text so that it replaces a string with user inputs and loop through a textand replace the conte

Time:01-12

I want to swap text so that it replaces a string (ie "electric") within any given text that the user inputs in a form cell. Then loop through the span elements in the text and replace their contents with the input text.

function swap_text() {
    var input_text = document.getElementById("input_text").value;


    var spans = document.getElementById("text").getElementsByTagName("span");

CodePudding user response:

I think what might be confusing you is that .getElementsByTagName("span") returns an HTMLCollection, not an array.

One approach is to convert that to an array, then you can simply loop the array and set the text.

function swapText() {
    const inputText = document.getElementById("input_text").value;

    const spans = document.getElementById("text").getElementsByTagName("span");

    Array.from(spans).forEach(span => {
        span.innerText = "some text"
    })
}

A few tips (although they are subject to preference):

  1. By convention JavaScript is typically written using camelCase.
  2. Use const instead of var if you don't plan to change the variable, it's helpful for other devs to read it and know that it won't change later.
  3. Prefer let over var until you truely understand the difference between the two.

CodePudding user response:

The HTML the function is expected to be applied upon was loosely described but not actually provided by the OP. I hope it looks something like in the following snippet:

const spans=document.querySelectorAll("#text span"),
 inp=document.querySelector("#repl");
inp.addEventListener("input",()=>spans.forEach(sp=>sp.textContent=inp.value));
span {color:orange}
<input id="repl" type="text" placeholder="enter new text for spans here!" size="20">
<h2>My text</h2>
<p>It starts with a paragraph that is <span>not</span> to be changed.</p>

<div id="text">
<p>Followed by a few few paragraphs in which each each <span>placeholder</span> is expected to be replaced by the user's input.<p>
<p>This should also happen here: <span>another placeholder</span> and here: <span>yet another one</span>.</p>
</div>

The document.querySelectorAll("#text span") returns all <spans> that are found within the specified DOM element with id="text" in a "collection". This collection is not an actual JavaScript array, but unlike the HTMLCollection returned by element.getElementsByTagName() it has also a method .forEach() which I can then directly use to replace each selected element's .textContent with the user-entered inp.value.

  • Related