dojo.byId

 

dojo.byId

Status:Draft
Version:1.0
Available:since V?

This is a simple alias to ''document.getElementById'', which not only is shorter to write, but fortunately works in all browsers. It turns a domNode reference to some Node byId, or the same node reference if passed a domNode.

1
2
// fetch a node by id="someNode"

var node = dojo . byId ( "someNode" );

The node variable is just a native domNode, with properties you can manipulate. The most common, ''innerHTML'':

1
2
// set some node to say "Hello World"

dojo . byId ( "someNode" ). innerHTML = "Hello World" ;

If you pass byId a domNode reference, the same node is returned:

1
2
3
4
var
 node
 =
 dojo
.
byId
(
"someNode"
);

var other = dojo . byId ( node );
console . log ( node == other );
>>> true

If you pass dojo.byId a string, and no domNode is found to match, ''undefined'' or the null object is returned (depending on the browser), which is adequate truthiness to use conditionally:

1
2
3
4
5
6
var
 node
 =
 dojo
.
byId
(
"fooBar"
);

if ( node ){
node . innerHTML = "I was found!" ;
} else {
console . log ( "no node with id='fooBar' found!" );
}

Most (if not all) functions in Dojo accept either a string or DomNode as a parameter. If passed a string, the function typically calls dojo.byId(), ensuring a domNode is always the object. For instance:

1
2
3
dojo
.
style
(
dojo
.
byId
(
"foo"
)
,
 "opacity"
,
 0.5
);

// is identical to:
dojo . style ( "foo" , "opacity" , 0.5 );

The latter is preferred, as the call to dojo.byId is made in both cases. The passing of a string ID is consistent throughout the Dojo Toolkit.

JavaScript has a fun convention for conditionals inline. Imagine wanting a domNode reference, and if not present, default to some other node:

1
2
3
var
 othernode
 =
 dojo
.
byId
(
"fallbackNode"
);

var node = dojo . byId ( "missingNode" ) || othernode ;
node . innerHTML = "Which one?" ;

Above, if the node id="missingNode" is in fact missing, the logical OR will continue, and use othernode as the value of node.

Examples

Fade-out a node

The following example lets a node by id dissapear from the screen

See Also
References
  • DOM - Official documentation on the Document Object Model.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值