最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

division - Javascript length of a div says undefined - Stack Overflow

programmeradmin1浏览0评论

I have a div with id user. When I check it's length it says undefined even when it exists.

<div id="user"></div>

I use pure javascript like below.

var user = document.getElementById("user").length;
console.log(user);

Any idea how to check the length without using jQuery?

I have a div with id user. When I check it's length it says undefined even when it exists.

<div id="user"></div>

I use pure javascript like below.

var user = document.getElementById("user").length;
console.log(user);

Any idea how to check the length without using jQuery?

Share Improve this question asked Dec 21, 2015 at 17:30 Joel JamesJoel James 1,3451 gold badge20 silver badges38 bronze badges 8
  • 13 What is a div's length? – Musa Commented Dec 21, 2015 at 17:32
  • But I tried using Firebug console too. – Joel James Commented Dec 21, 2015 at 17:33
  • @Musa it is 1 as you can see. – Joel James Commented Dec 21, 2015 at 17:33
  • 2 length on a jquery object is a special property since jQuery always returns an array of objects, sometimes of length 0 if it finds nothing. Length on a regular DOM node is not a valid property. What are you trying to achieve specifically? – AtheistP3ace Commented Dec 21, 2015 at 17:35
  • 1 What kind of result do you expect from document.getElementById("user").length? – Holt Commented Dec 21, 2015 at 17:37
 |  Show 3 more ments

2 Answers 2

Reset to default 8

You seem to want to check the element exists.

In the case of a single DOM element (not a collection), there's no need to check the length.

var user = document.getElementById("user");
var divExists = user != null;
alert(divExists);
<div id="user"></div>

Note: when using a function returning a NodeList, like querySelectorAll, checking the length might be useful.

getElementById returns 1 element (if found) or null, and the length property for a Dom element is not defined, that's why you're getting undefined. So you basically just have to check whether the element exists...

var user = document.getElementById("user");
if (user) { //... Whatever }

Returns a reference to the element by its ID; the ID is a string which can be used to identify the element; it can be established using the id attribute in HTML, or from script. [...] If there is no element with the given id, this function returns null.

cfr. https://developer.mozilla/en-US/docs/Web/API/Document/getElementById

发布评论

评论列表(0)

  1. 暂无评论