开发者

How to detect if Javascript/JQuery object has a height?

开发者 https://www.devze.com 2023-03-25 19:40 出处:网络
I开发者_如何转开发\'m iterating through a DOM to change the display characteristics of different elements. I loop through the elements, and use the JQuery .height() method to get a height:

I开发者_如何转开发'm iterating through a DOM to change the display characteristics of different elements. I loop through the elements, and use the JQuery .height() method to get a height:

var myHeight = myJQueryElement.height();

Trouble is, when I hit a "comment" element in Firefox, I get this error:

Error: uncaught exception: [Exception... "Could not convert JavaScript argument arg 0 [nsIDOMViewCSS.getComputedStyle]" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js :: :: line 18" data: no]

Ok, fine, I can check the nodeType, right? No, oddly, when I call:

var nt = myJQueryElement.nodeType;

the nodeType is always "undefined". Weird, because when I click on the element in the Javascript debugger in Firebug, it show me a correct nodeType of 8.

All I want to do is check whether the element has a height > 0, and skip it otherwise.

Any clues how to do this?


You need to check the DOM node, not the jQuery object.

 // ----------------------v----extract the DOM node at index 0
var nt = myJQueryElement[ 0 ].nodeType;


I can recreate your error when iterating the <body> like so:

var body = document.getElementsByTagName('body')[0];

for (var i in body.children) {
    console.log(body.children[i]);
    console.log($(body.children[i]).nodeType);
}

But I don't get the error when iterating with .each()

$('body').children().each(function() {
    console.log($(this).height());
});

maybe use .each() with recursion to iterate through the DOM elements

0

精彩评论

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