Home > Blockchain >  How to declare a value selected in HTML as a variable?
How to declare a value selected in HTML as a variable?

Time:05-27

I have the following code:

<span id="text">Change</span>
<P>
<select >
    <option value=X1a selected>X1a</option>
    <option value=X2a>X2a</option>
    <option value=X3a>X3a</option>
    <option value=X4a>X4a</option>
</select>
<P>
<span id="WW"></span>
<script>
    let X1a = '"Hello"'
    let X2a = '"Watcha"'
    let X3a = '"Hiya"'
    let X4a = '"YouHoo"'
    let ZZ = text
    document.getElementById("WW").innerHTML = ZZ;
</script>

As you can see, I am selecting a value with id=text. I now want the value in "text" to be a variable in the document.getElementById line to print out the appropriate greeting. But it outputs [object HTMLSpanElement]. How do I make the value which I select a variable for the purposes of the document.getElementById line?

CodePudding user response:

I think you’re looking for the properties .textContent or .innerHTML. Here’s the differences: https://www.geeksforgeeks.org/difference-between-textcontent-and-innerhtml/. They both allow you to get the value inside a HTML tag. Here’s an example with your code:

let ZZ = document.getElementById("text")
document.getElementById("WW").innerHTML = ZZ.textContent;

CodePudding user response:

Answer: ZZ.textContent - MDN Node.textContent

However, I'd personally store a reference to the element using getElementById just to make it clear what I'm doing, like so:

let textElement = document.getElementById('text');
document.getElementById("WW").innerHTML = textElement.textContent

CodePudding user response:

I don't understand your problem very well. You can do :

let ZZ = document.getElementById("text").textContent
  • Related