Thank you in advance for your help:

I really don't know much about Javascript but I'm trying to use it on my web site.

Here is the code:

function changeCategory() {

//ID#1
	document.getElementById('category_106634').setAttribute("class","mind")
    document.getElementById('category_106634').innerHTML="MIND"
    document.getElementById('category_106634').href="http://www.voyagetobetterment.com/_blog/Voyage_to_Betterment_Blog/tag/MIND/"

//ID#2
	document.getElementById('category_106446').setAttribute("class","movie")
    document.getElementById('category_106446').innerHTML="MOVIE"
    document.getElementById('category_106446').href="http://www.voyagetobetterment.com/_blog/Voyage_to_Betterment_Blog/tag/MOVIE/"

}

The program works fine if the ELEMENT#1 is above ELEMENT#2 in the html. If ELEMENT#2 is above ELEMENT#1 in the html, the program doesn't work. If ELEMENT#1 isn't on the page, ELEMENT#2 won't work.

How do I get this program to work regardless of whether ELEMENT1 or ELEMENT2 is in the html code or not?

Recommended Answers

All 2 Replies

The reason may be that your element ID cannot be found in HTML; as a result, JavaScript will stop working right where the error is found. Here is an example for fixing it.

function changeCategory() {
  // you don't need to call getElementById all the time, you can assign the
  // object to a variable, and then use it anywhere locally.
  var el1 = document.getElementById('category_106634')
  var el2 = document.getElementById('category_106446')

  //ID#1
  if (el1) {  // let it go through if found ID 'category_106634' element in the page
    el1.setAttribute("class","mind")
    el1.innerHTML="MIND"
    el1.href="http://www.voyagetobetterment.com/_blog/Voyage_to_Betterment_Blog/tag/MIND/"
  }

  //ID#2
  if (el2) {  // again check if found the ID 'category_106446'
    el2.setAttribute("class","movie")
    el2.innerHTML="MOVIE"
    el2.href="http://www.voyagetobetterment.com/_blog/Voyage_to_Betterment_Blog/tag/MOVIE/"
  }
}

That if statement is exactly what I needed to know, thank you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.