Home > OS >  Selecting multiple elements with querySelectorAll and applying event in JavaScript
Selecting multiple elements with querySelectorAll and applying event in JavaScript

Time:02-13

there is an onchange event on the input and want it to change the value of the spans with the class of "number" whenever it changes so there here is the HTML :

    <div >
        <p>Metric/Imperial unit conversion</p>
//***********************************************************************************************
         //this input will change the value of 6's span below with the class of "number"
//**********************************************************************************************
        <input type="text" id="myText"  placeholder="number here" value="20" 
        onchange="myFunction()">
    </div>
    <div >
        <p>Length(Meter/Feet)</p>
            <p>
                <span ></span> meters = <span ></span>feet |
                <span ></span> feet = <span ></span>meters
            </p>
        <p>Volume(Liters/Gallons)<</p>
            <p>
                <span ></span> liter = <span ></span>gallon |
                <span ></span> gallon = <span ></span>liter
            </p>
        <p>Mass(Kilograms/Pounds)</p>
            <p>
                <span ></span> kilogram = <span ></span>pound |
                <span ></span> pound = <span ></span>kilogram
            </p>
    </div>

and this is the JavaScript side :

     function myFunction() {
        var x = document.getElementById("myText").value
        document.querySelectorAll(".number").innerText = x
     }

so how to make spans with the have the same value as input id="myText"? and one thing to mention is that I use scrimba editor.

CodePudding user response:

Unlike jQuery, Vanilla JS will not execute innerText to every node returned by querySelectorAll with an inline call. You would need to loop through them.

The code below should work:

function myFunction() {
    var x = document.getElementById("myText").value;
    var spans = document.querySelectorAll(".number");
    for (let i = 0; i < spans.length; i  ) {
        spans[i].innerText = x;
    }
}

CodePudding user response:

You can also use the for-of loop.

function myFunction() {
    const x = document.getElementById("myText").value;
    const numberElements = document.querySelectorAll(".number");

    for (let element of numberElements) {
        element.innerText = x;
    }
}
  • Related