I have a simple function constructor and want to assign a DOM element ID to one of the properties. When this is done outside of a constructor you have to put the ID in quotation marks IE getElementById(” whatever “);
In my constructor I am not sure if I need to do this, how do add them, nor if I am formatting this correctly.
<form id="form">
<input type="text" id="bookText" value="Book">
</form>
<script>
function Item(itemName,itemDomID){
this.itemName = document.getElementById(this.itemDomID);
};
var mybook = new Item(book,bookText); // new object.
</script>
An element ID is a string, assigning a string to an object property does not require a function, just an assignment:
When passing values using variables, just use the variable name. The expression will be evaluated to return the value. The constructor should be (note changes to original):
Note the use of square brackets to assign the value of
itemNameto the new property name, rather than the literal string “itemName”.So when calling the constructor, string values can be passed:
The values will be assigned to the variables in the function in order, so
itemNameis assigned the value “book” anditemDomIDis assigned the value “bookText”.Inside the constructor, the new object will be given a property named “book” with a value of whatever is returned by
document.getElementById('bookText'), which will either be a reference to an element, ornullif no element with that ID is found.