2

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?

Code Lღver
  • 15,573
  • 16
  • 56
  • 75
8fan
  • 23
  • 5
  • With [jQuery](http://jquery.com/): `$('#ID').html('Something').css({ display: 'some', color: '#CCC' })`, you can put line breaks before the method calls obviously. – Fabrício Matté Sep 23 '13 at 11:14
  • possible duplicate of [How do I implement a Chaining Pattern like jQuery does?](http://stackoverflow.com/questions/18862623/how-do-i-implement-a-chaining-pattern-like-jquery-does) – Claudio Santos Sep 23 '13 at 11:24

4 Answers4

2

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.

Code Lღver
  • 15,573
  • 16
  • 56
  • 75
1

Take document.getElementById("ID") into a variable.

Like

var eleId = document.getElementById("ID");

eleId.innerHTML = "Something"; 
eleId.style.display = "some";
eleId.style.color = "#CCC";
Naveen Kumar Alone
  • 7,536
  • 5
  • 36
  • 57
0

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.

iConnor
  • 19,997
  • 14
  • 62
  • 97
0

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";
Roy Miloh
  • 3,381
  • 1
  • 18
  • 17