Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to target elements in li with javascript

Here is a code of javascript for example i want to change the text in the span that is nested in li. How do i use the DOM to target this elements ?

var body = document.getElementsByTagName('body')[0]
body.style.fontFamily = "Arial";
var name = document.getElementsById('name');
var index = document.getElementsById('index');
var hometown = document.getElementsById('hometown');
name.innerHTML = "NAME";
index.innerHTML = "INDEX";
hometown.innerHTML = "HOMETOWN";
<h1>About Me</h1>
<ul>
  <li>Name: <span id="name"></span>
    <li>Index: <span id="index"></span>
      <li>Hometown: <span id="hometown"></span>
</ul>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • Typo: getElementById is singular – it is getElementById and not getElementsById
  • Also don’t have a var with the same name as an ID in the page – it hides the var
  • Also please close the <li> for formatting reasons
var body = document.getElementsByTagName('body')[0]
body.style.fontFamily = "Arial";
var nameSpan = document.getElementById('name'); // either change the var or the ID - I suggest the ID since name is used in several places like window.name etc
var index = document.getElementById('index');
var hometown = document.getElementById('hometown');
nameSpan.innerHTML = "NAME";
index.innerHTML = "INDEX";
hometown.innerHTML = "HOMETOWN";
<h1>About Me</h1>
<ul>
  <li>Name: <span id="name"></span></li>
  <li>Index: <span id="index"></span></li>
  <li>Hometown: <span id="hometown"></span></li>
</ul>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading