codestudent
codestudent

Reputation: 73

How do I style a tag within an ID using Javascript?

I'm trying to style the li elements within the "eventsList" ID in this HTML file using Javascript. I've been playing around with the code and for whatever reason, the styling isn't working. I feel like this must be a super easy solution, but being a newbie, I can't get it figured out. The first four bullet points should be styled in bold and with an orange font color, if it were working.

function findElements() {
  var events = getElementById('eventsList');
  var linkItems = events.getElementsByTagName('li');
  
  for (var i = 0; i < linkItems.length; ++i) {
    linkItems[i].style.color = 'orange';
    linkItems[i].style.fontWeight = 'bold';
  }
}

window.onload = findElements;
<h2>Subheading</h2>
<ul id="eventsList">
  <li>List 1</li>
  <li>List 2</li>
  <li><a href="www.google.com">Linked list Item</a></li>
  <li>List 4</li>
</ul>

What am I doing wrong?

Upvotes: 1

Views: 66

Answers (3)

Jason Pelletier
Jason Pelletier

Reputation: 161

You're really close! Just some basic errors. You need to execute the function at the bottom and you need to get eventsList from the document.

function findElements() {
  var events = window.document.getElementById('eventsList');
  var linkItems = events.getElementsByTagName('li');
  for (var i=0; i< linkItems.length;++i) {
    linkItems[i].style.color="orange";
    linkItems[i].style.fontWeight="bold";
  }
}
window.onload = findElements();

Upvotes: 1

Mike Cluck
Mike Cluck

Reputation: 32511

You've got one little problem. getElementById doesn't exist on it's own. It is a property of document. The corrected line looks like this:

var events = document.getElementById('eventsList');

For future problems, here's how you can discover the issue for yourself. Open your developer tools (F12 in many browsers) and look in the console. You'll see an error saying that getElementById is not defined. That's a reminder to make sure you're referencing the right method and on the right object.

Upvotes: 1

spidyx
spidyx

Reputation: 1117

You must use document.getElementById :

function findElements() {
  var events = document.getElementById('eventsList');
  var linkItems = events.getElementsByTagName('li');
  for (var i=0; i< linkItems.length;++i) {
    linkItems[i].style.color="orange";
    linkItems[i].style.fontWeight="bold";
  }
}
window.onload = findElements;
  <ul id="eventsList">
    <li>List 1</li>
    <li>List 2</li>
    <li><a href="www.google.com">Linked list Item</a></li>
    <li>List 4</li>
  </ul>

Upvotes: 4

Related Questions