Question

if (this.firstChild.style.display == 'none')
{this.firstChild.style.display = 'block'}
else
{this.firstChild.style.display = 'none'};

Is it possible to shorten this code using variables?

Was it helpful?

Solution

you can shorten it like this:

var a = this.firstChild.style;
a.display = (a.display=='none'?'block':'none');

OTHER TIPS

var childStyle=this.firstChild.style;
if ( childStyle.display == 'none'){
    childStyle.display = 'block';
}
else{
    childStyle.display = 'none';
}

will be the equivalent.

You can shorten in further using ternary operator like

var childStyle=this.firstChild.style;
childStyle.display=(childStyle.display=='none')?'block':'none';

If you go for jquery than its shorten than this

$("div span:first-child").toggle();

or

$(this).find(">:first-child").toggle();

By the way, can this be another alternative?

with this.firstChild.style.display{this=(this=='none')?'block':'none';}

try:

var elstyle = this.firstChild.style;
elstyle.display = /block/i.test(elstyle.display) ? 'none' : 'block'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top