简体   繁体   中英

How can I link a JavaScript variable to a HTML value?

I need to link an item in a table to a Javascript variable, but it won't link. I think there will be further problems changing the value.

I am running on Atom Editor, with the script package installed, although I could copy the script into Notepad++ or Brackets if needed.

</tr>
    <td>Abena</td>
    <td>Natale</td>
    <td id = "Abena_Natale">11782</td>
    <td>No.1</td>
    <td>Monarch of Boars</td>
</tr>

<script>
var Abena_Natale = ""

</script>

I expected to get a variable that would change the value in the Abena_Natale element when the Javascript stated. Instead, it just stays the same.

There was an error in your HTML. From there we need to write the selector to get the element. And then grab the content inside the node.

Update to support editing.

 var Abena_Natale = ""; var abenaElement; document.addEventListener('DOMContentLoaded', function() { abenaElement = document.querySelector('#Abena_Natale'); Abena_Natale = abenaElement.innerHTML; console.log(Abena_Natale); // Update the value abenaElement.innerHTML = "Testing"; }); 
 <table> <tr> <td>Abena</td> <td>Natale</td> <td id="Abena_Natale">11782</td> <td>No.1</td> <td>Monarch of Boars</td> </tr> </table> 

That's not how you access the Document Object Model (DOM) with JS. You need to grab the element using one from a number of methods, and then amend the data.

1) Make sure your table row elements are opened and closed correctly.

2) Use either document.getElementById('Abena_Natale') , or document.querySelector('#Abena_Natale') to grab the element.

3) Set the textContent of the element. value is generally used for input elements.

 const aN = document.getElementById('Abena_Natale'); aN.textContent = 'This has been changed'; 
 <table> <tr> <td>Abena</td> <td>Natale</td> <td id="Abena_Natale">11782</td> <td>No.1</td> <td>Monarch of Boars</td> </tr> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM