开发者

Multiple class query not working

I have this HTML-element:

<div class="option default"></开发者_StackOverflow社区div>

...and I try to get to it in Dojo like this:

var el = dojo.query(".option.default");

But when I try:

alert(dojo.attr(el, "class"));

...I get undefined.

Update:

For some reason, this works:

alert(el.attr("class"));

How come the other method doesn't work?


dojo.query() returns a list of DOM nodes based on a CSS selector, not a single element. You would need to do:

var els = dojo.query(".option.default");
var el = els[0];
alert(dojo.attr(el, "class"));

Here's a working example: http://jsfiddle.net/ArtBIT/L35k6/


Would add to the comment but I can't.

@Orolin, how does Dojo know that you know you're expecting a single Node to be returned. If it special cased single elements then anywhere you call dojo.query() and genuinely don't know how many elements you're expecting to get back, you'd have to test yourself. That would be horrid, and take more than three characters!

If you really want this functionality, just do one of the following:

dojo.queryFirst = function() {
    return(dojo.query(arguments)[0]);
}

or, if you must

dojo._oldQuery = dojo.query;
dojo.query = function() {
    var nodes = dojo._oldQuery(arguments);
    return nodes.length > 1 ? nodes : nodes[0];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜