JavaScript determines the existence of elements and determines the way elements exist in real-time DOM

Source: Internet
Author: User
Tags baseuri mozilla developer network

Today (Saturday) afternoon when I was working overtime in the company do not know what to do, open the company's WordPress project site, want to see a Web page before you do not have a problem.

Open the website homepage, I habitually opened the Chrome debugging tool, and then the mouse began to scroll the page, then the question came out: the page cannot scroll down, the Debugging tool console has reported many undefined errors.

I immediately realized that I wrote the error of JS code in the homepage was executed caused by the problem, my code is roughly like this:

1 if ($ (' #a ')) {2   // some code ... 3   $ (' #b '). dosomething; 4   // some code ... 5 }
View Code

What this code wants to do is to determine whether the page has an element identified by an ID, and if so, do something about it. The homepage of the website should not have this element, should not execute this code.

Well, if you see this, you can probably guess I'm not a front-end. I expect it to return a Boolean type of false, but it actually returns a jquery Object,

Note that this is not a DOM element, and if you want to get the real DOM element, you can write $ (' #a ') [0] or $ (' #a '). Get (0).

The fact that $ (' selector ') returns is always a jquery Object, whether it finds an element or not. (Refer to the question about this return value: What does jquery $ actually return? And how to get a DOM Element from a jquery Selector).

So how can I tell if the elements of id=a exist? You can actually do this if($ (' #a '). Length), if there is no #a then the returned object is actually an empty object that can be used to achieve the purpose.

getElementById (' a ') Yes, it returns a reference (object type) of element object or null (document.getElementById ()), which can be used to judge.

Here, my problem is solved, there is no this article.

But I was busy and Google took a hand, and then I found this question on the StackOverflow: how to check if element exists in the visible DOM? The question is how to check if an element exists in the DOM that is visible (currently in real time) .

This question and answer mentioned a lot of methods, in addition to the above two mentioned methods, other such as Getelementsbyclassname, Getelementsbyname, Queryselector and so on, in short, these methods of thinking basic and the above two are the same, is simply checking to see if the element exists.

For the main question, someone has provided the following two interesting methods, one of which is: document.body.contains (Element), where the node.contains (Othernode) method is used, It can determine if Othernode is a descendant of node and returns a Boolean value.

The specific usage can be written like this:

1 // gets the element node to judge first 2 Const ANODE = document.getElementById (' a '); 3 4 // then determine if the element node is the descendant of the body node of the current document page 5 if (ANode.ownerDocument.body.contains (anode)) {6  // Do something 7 }
View Code

In fact, using this method can write a general function to determine whether an element node is on a page, you can refer to the Mozilla Developer Network website javascript manual code:

1 function isinpage (node) {2   return false : Document.body.contains (node); 3 }
View Code

In the code above, Anode.ownerdocument is a read-only property that returns the top-level Document object on the page where anode is located.

Another reference is made to this method: To determine whether the BaseURI of the element node exists.

BaseURI is a read-only property, Node.baseuri returns the absolute base URL address of the node (which I interpret as the absolute URL address of the page), such as $ (' #a ') [0].baseuri,

I tried under chrome, #a元素存在的话就会返回一个url字符串, does not exist in the undefined error (#a不存在自然会报这个错误), feel this method in practical application is not very good operation, to throw and catch errors, interested students can study.

How to check if element exists in the visible DOM? The initiator of this question wrote himself a method, and I pasted the code below:

1<! DOCTYPE html>234<script>5     varGetrandomid =function(size) {6             varstr = "",7i = 0,8chars = "0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ";9              while(I <size) {Tenstr + = CHARS.SUBSTR (Math.floor (Math.random () * 62), 1); Onei++; A             } -             returnstr; -         }, theIsNull =function(Element) { -             varRandomid = Getrandomid (12), -Savedid = (element.id)? Element.id:NULL; -Element.id =Randomid; +             varFoundelm =document.getElementById (randomid); -Element.removeattribute (' id '); +             if(Savedid!==NULL) { AElement.id =Savedid; at             } -             return(Foundelm)?false:true; -         }; -Window.onload =function () { -         varImage = document.getElementById ("Demo"); -Console.log (' Undefined ', (typeofImage = = = ' undefined ')?true:false);//false inConsole.log (' null ', (image = = =NULL) ?true:false);//false -Console.log (' Find-by-id ', isNull (image));//false to Image.parentNode.removeChild (image); +Console.log (' Undefined ', (typeofImage = = = ' undefined ')?true:false);//false ~ should be true? -Console.log (' null ', (image = = =NULL) ?true:false);//false ~ should be true? theConsole.log (' Find-by-id ', isNull (image));//true ~ Correct but there must is a better how than this? *     }; $</script>Panax Notoginseng -<body> the<div id= "Demo" ></div> +</body> AView Code

Note the IsNull function in the code, which is used to determine whether the element exists, this method is actually based on whether the ID of the element is null to judge, the idea seems to be the same as with the baseuri to judge. I tried to return true when the element was present,

But when the element does not exist, it will be reported undefined error, interested students can study under.

Summarize:

It is simple and straightforward to judge whether an element exists, use getElementById () (or other method of selecting elements) to match whether it is null, or use jquery to get the object and judge its length.

But if you want to determine whether an element is in the DOM that is currently visible in real time, then use the Node.contains (Othernode) method.

Reference:

1,how to check if element exists in the visible DOM?

2,what does jquery $ actually return?

2,node.contains ()

3,node.ownerdocument

4,how to get a DOM Element from a JQuery Selector

5,https://api.jquery.com/get/

6,baseuri

PS: Feel more tired to write a blog than write code, write something yourself, in case you forget.

JavaScript determines the existence of elements and determines the way elements exist in real-time DOM

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.