Leia
Leia

Reputation: 357

Using getElementById inside a function (JavaScript)

I'm new to JavaScript and after trying many times to create a "shortcut" to use getElementById inside a function I almost gave up. I know there's something wrong with this but I can't find the error.

This is the HTML

<body> 
    <table>
        <tr>
            <td>Name: </td>
            <td id="name"></td>
        </tr>
    </table>
<script src="JS/return.js"></script>

and this is the JavaScript code:

var hotel = {
  name: "Park",
  roomRate: 240,
  discount: 15 / 100,
  offerPrice: function() {
    var offerRate = this.roomRate - (this.roomRate * this.discount);
    return offerRate;
  }
};

function element(idName, text) {
  var idd = document.getElementById(idName).textContent = text;
}

element(name, hotel.name);

I appreciate any help I can get :)

EDIT:

Thank you! the correct code is as follows:

function element(idName, text) {
  var idd = document.getElementById(idName).textContent = text;
}

element("name", hotel.name);

Upvotes: 0

Views: 8768

Answers (3)

Fares M.
Fares M.

Reputation: 1538

Try this

function element(idName, text) {
    var idd = document.getElementById(idName);
    idd.textContent = text;
}

element("name", hotel.name);

first, get the element and then modify its content separately

http://jsfiddle.net/h40qrdwg/

Upvotes: 1

Laurent
Laurent

Reputation: 1584

You're passing a variable called name into the function, but you haven't defined it in your code.

If you want to keep the naming flexible, just define the variable in your script as follows:

var name = "name";

If you're set on passing the id, just pass the string "name" through the method.

The important thing to understand here is that you need to pass the string of the ID through your method, either as a variable that is equal to the string, or the string itself.

Also if you want to manipulate the object after you've defined it, you need to return it. But one problem at a time!

Upvotes: 0

dark_ruby
dark_ruby

Reputation: 7866

You need to define a variable that you use as first parameter in element

//need to define a name first
var name = "name"; 

function element(idName, text) {
    document.getElementById(idName).textContent = text;
}

element(name, hotel.name);

Upvotes: 0

Related Questions