Reputation: 23
In JavaScript, Is it Possible to write Multi-Line Statement like as follows;
document.getElementById("ID").innerHTML = "Something";
.style.display = "some";
.style.color = "#CCC";
Hope you got the Idea?
Upvotes: 2
Views: 1180
Reputation: 20189
Well it all depends, in the example you have provided you cant do that, you can only do that when you call a function that also returns a function a good example is jQuery, lets take a look.
$('#something') // <-- select a element - returns a whole object of functions
.hide() // hide function was returned
.show() // show function was returned
.css(...);
In your example the string that you set was actually returned.
This is how you make a chaining function.
var test = function( name ) {
this.name = name;
return this;
};
test.prototype.viewName = function() {
console.log(this.name);
};
test.prototype.showName = function() {
alert(this.name);
return this;
};
var john = new test('john');
john.showName().viewName();
So in your case you would have to store the object
var element = document.getElementById("ID");
element.innerHTML = "Something";
element.style.display = "some";
element.style.color = "#CCC";
So it all depends on what is returned from your last action.
Upvotes: 0
Reputation: 3411
Well, it is, but not in your case.
It is possible when you call several functions which return the same obj over and over again, for instance in jQuery:
$('#el').fadeIn().fadeOut();
It's called Cascade
(Well, Douglas Crockford called it like that, you can find it in his book Javascript: The Good Parts
)
In your case you cannot do that (at least with vanilla javascript).
var el = document.getElementById("ID")
el.innerHTML = "Something";
el.style.display = "some";
el.style.color = "#CCC";
Upvotes: 0
Reputation: 15603
No, You can't write like this but can use this:
var obj = document.getElementById("ID");
obj.innerHTML = "Something";
obj.style.display = "some";
obj.style.color = "#CCC";
Because to call any property in javascript there is need the object on which you want to apply that property.
Upvotes: 2
Reputation: 7668
Take document.getElementById("ID")
into a variable.
Like
var eleId = document.getElementById("ID");
eleId.innerHTML = "Something";
eleId.style.display = "some";
eleId.style.color = "#CCC";
Upvotes: 1