javascript - Making element referencing less clunky -


I'm new to JavaScript so please forgive me if this is a simple answer. I can not know that I have a small section of the script that changes the text based on the content of the paragraph. Very easy. My question is, why do I have to complete the entire context twice? Does the variable not point to the same thing? Is there an easier way?

This works:

  & lt; P id = "name" & gt; Electric City & lt; / P & gt; & Lt; Script type = "text / javascript" & gt; Var name = document.getElementById ("name"). InnerHTML; If (name == "electric city") {document.getElementById ("name"). InnerHTML = "Welcome!"; } & Lt; / Script & gt;   

It is not:

  & lt; P id = "name" & gt; Electric City & lt; / P & gt; & Lt; Script type = "text / javascript" & gt; Var name = document.getElementById ("name"). InnerHTML; If (name == "Electric City") {name = "Welcome!"; } & Lt; / Script & gt;   

Thanks!

  var name = document .getElementById ("name") innerHTML.   

That line of code gets value from your "name" element (using its innerHTML property) and its variable Copies in names . The name variable does not reference the "name" element.

If you want to simplify your code, then you can do something like this:

  & lt; script type = "text / javascript" & gt; Var name element = document.getElementById ("name"); If (nameElement.innerHTML == "Electric City") {nameElement.innerHTML = "Welcome!" ;; } & Lt; / Script & gt;    

Comments

Popular posts from this blog

Java - Error: no suitable method found for add(int, java.lang.String) -

java - JPA TypedQuery: Parameter value element did not match expected type -

c++ - static template member variable has internal linkage but is not defined -