Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

javascript - 如何检查可见DOM中是否存在元素?(How to check if element exists in the visible DOM?)

How do you test an element for existence without the use of the getElementById method?

(如何在不使用getElementById方法的情况下测试元素是否存在?)

I have setup a live demo for reference.

(我已经设置了一个现场演示供参考。)

I will also print the code on here as well:

(我也会在这里打印代码:)

<!DOCTYPE html>
<html>
<head>
    <script>
    var getRandomID = function (size) {
            var str = "",
                i = 0,
                chars = "0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ";
            while (i < size) {
                str += chars.substr(Math.floor(Math.random() * 62), 1);
                i++;
            }
            return str;
        },
        isNull = function (element) {
            var randomID = getRandomID(12),
                savedID = (element.id)? element.id : null;
            element.id = randomID;
            var foundElm = document.getElementById(randomID);
            element.removeAttribute('id');
            if (savedID !== null) {
                element.id = savedID;
            }
            return (foundElm) ? false : true;
        };
    window.onload = function () {
        var image = document.getElementById("demo");
        console.log('undefined', (typeof image === 'undefined') ? true : false); // false
        console.log('null', (image === null) ? true : false); // false
        console.log('find-by-id', isNull(image)); // false
        image.parentNode.removeChild(image);
        console.log('undefined', (typeof image === 'undefined') ? true : false); // false ~ should be true?
        console.log('null', (image === null) ? true : false); // false ~ should be true?
        console.log('find-by-id', isNull(image)); // true ~ correct but there must be a better way than this?
    };
    </script>
</head>
<body>
    <div id="demo"></div>
</body>
</html>

Basically what the above code demonstrates is an element being stored into a variable and then removed from dom.

(基本上上面代码演示的是一个元素存储到变量中然后从dom中删除。)

Even though the element has been removed from the dom, the variable retains the element as it was when first declared.

(即使元素已从dom中删除,该变量仍保留元素,就像第一次声明时一样。)

In other words, it is not a live reference to the element itself, but rather a replica.

(换句话说,它不是元素本身的实时引用,而是副本。)

As a result, checking the variable's value (the element) for existence will provide an unexpected result.

(因此,检查变量的值(元素)是否存在将提供意外结果。)

The isNull function is my attempt to check for an elements existence from a variable, and it works, but I would like to know if there is an easier way to accomplish the same result.

(isNull函数是我尝试从变量中检查元素是否存在,并且它有效,但我想知道是否有更简单的方法来实现相同的结果。)

PS: I'm also interested in why JavaScript variables behave like this if anyone knows of some good articles related to the subject.

(PS:如果有人知道一些与该主题相关的好文章,我也对JavaScript变量的行为感兴趣。)

  ask by Justin Bull translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It seems some people are landing here, and simply want to know if an element exists (a little bit different to the original question).

(似乎有些人正在这里登陆,只是想知道一个元素是否存在 (与原始问题有点不同)。)

That's as simple as using any of the browser's selecting method, and checking it for a truthy value (generally).

(这就像使用任何浏览器的选择方法一样简单,并检查它的真实值(通常)。)

For example, if my element had an id of "find-me" , I could simply use...

(例如,如果我的元素的id"find-me" ,我可以简单地使用...)

var elementExists = document.getElementById("find-me");

This is spec'd to either return a reference to the element or null .

(这被指定要么返回对元素的引用,要么返回null 。)

If you must have a Boolean value, simply toss a !!

(如果你必须有一个布尔值,只需扔一个!!)

before the method call.

(在方法调用之前。)

In addition, you can use some of the many other methods that exist for finding elements, such as (all living off document ):

(此外,您可以使用其他许多方法来查找元素,例如(所有生活在document ):)

  • querySelector() / querySelectorAll()

    (querySelector() / querySelectorAll())

  • getElementsByClassName()
  • getElementsByName()

Some of these methods return a NodeList , so be sure to check its length property, because a NodeList is an object, and therefore truthy .

(其中一些方法返回一个NodeList ,因此请务必检查其length属性,因为NodeList是一个对象,因此是真实的 。)


For actually determining if an element exists as part of the visible DOM (like the question originally asked), Csuwldcat provides a better solution than rolling your own (as this answer used to contain).

(为了实际确定一个元素是否作为可见DOM的一部分存在(如最初提出的问题), Csuwldcat提供了一个比滚动自己更好的解决方案 (如此答案所包含)。)

That is, to use the contains() method on DOM elements.

(也就是说,在DOM元素上使用contains()方法。)

You could use it like so...

(你可以像这样使用它......)

document.body.contains(someReferenceToADomElement);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...