dojo.byId

来源:互联网 发布:广联达预算软件官网 编辑:程序博客网 时间:2024/05/12 07:35
 

dojo.byId

Status:DraftVersion:1.0Available:since V?

Contents

  • Examples
    • Fade-out a node
    • See Also
    • References

This is a simple alias to ''document.getElementById'', which notonly is shorter to write, but fortunately works in all browsers. Itturns a domNode reference to some Node byId, or the same node referenceif 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 nodomNode is found to match, ''undefined'' or the null object is returned(depending on the browser), which is adequate truthiness to useconditionally:

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 accepteither a string or DomNode as a parameter. If passed a string, thefunction typically calls dojo.byId(), ensuring a domNode is always theobject. 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 todojo.byId is made in both cases. The passing of a string ID isconsistent throughout the Dojo Toolkit.

JavaScript has a fun convention for conditionals inline. Imaginewanting a domNode reference, and if not present, default to some othernode:

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

  • dijit.byId - Accessing a Dijit widget by id.

References

  • DOM - Official documentation on the Document Object Model.
原创粉丝点击