javascript method for judging the presence of elements and judging the presence of elements in real time dom

  • 2021-07-12 04:56:38
  • OfStack

Today (Saturday) afternoon, when I was working overtime in the company, I didn't know what to do, so I opened an wordpress project website of the company and wanted to see if there was any problem with a webpage I had made before.

Open the home page of the website, I habitually opened the debugging tool of chrome, and then the mouse began to scroll the page, and then the problem came out: the page could not scroll down, and the debugging tool reported a lot of undefined errors in console.

I immediately realized that the problem was caused by the wrong execution of the js code I wrote on the front page. My code is roughly like this:


if ($('#a')) {
 // some code ...
 $('#b').doSomething;
 // some code ...
 }

What this code wants to do is to determine whether the next page has an id logo element, and if so, do something. The homepage of the website should not have this element, and this code should not be executed.

Well, if you see here, you can guess that I'm not a front-end. I expect it to return a Boolean false, but it actually returns an jQuery Object,

Note that what you get here is not dom element. If you want to get the real dom element, you can write $('# a') [0] or $('# a'). get (0).

In fact, $('selector') always returns an jQuery Object, regardless of whether it finds the element or not. (For questions about this return value, please refer to: What does jquery $actually return? And How to get a DOM Element from a JQuery Selector).

So how do I judge whether the element id=a exists? You can actually do this, if ($('# a'). length). If there is no # a, the returned object is actually an empty object, which can achieve your goal.

Is getElementById ('a') OK? It returns a reference to Element object (object type) or null (document. getElementById ()), which can be used to judge.

At this point, my problem is solved, and there is no such article.

But I got another google when I was idle, and then I found this question and answer on stackoverflow: How to check if element exists in the visible DOM? The problem is how to check whether the element exists in the visible (currently real-time) dom.

There are many methods mentioned in this question and answer, except the above two methods, such as getElementsByClassName, getElementsByName, querySelector, etc. In short, these methods are basically the same as the above two methods, that is, simply check whether elements exist.

For the subject's question, some people have provided the following two interesting methods, one of which is document. body. contains (element), in which node. contains (othernode) method is used, which can judge whether othernode is a descendant of node and return a Boolean value.

The specific usage can be written as follows:


//  Get the element node to be judged first 
const aNode = document.getElementById('a');
//  Then determine whether the element node is the current document page body Descendants of nodes 
if (aNode.ownerDocument.body.contains(aNode)) {
 // do something
}

In fact, with this method, you can write a general function to judge whether an element node is on a certain page. You can refer to the code in the Mozilla Developer Network official website javascript manual:


 function isInPage(node) {
 return (node === document.body) ? false : document.body.contains(node);
 }

aNode. ownerDocument in the above code is a read-only property that returns the top-level document object document on the page where aNode is located.

Someone else mentioned this method: to determine whether the baseURI of the element node exists or not.

baseURI is a read-only property, node. baseURI returns the absolute base url address of the node node (which I understand as the absolute url address of the page), such as $('# a') [0]. baseURI,

I tried under chrome, if the # a element exists, it will return an url string. If it does not exist, it will report an undefined error (if # a does not exist, it will naturally report this error). I feel that this method is not easy to operate in practical application. To throw and capture errors, interested students can study it.

How to check if element exists in the visible DOM? The initiator of this question and answer wrote his own method, and I posted the code below:


<!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>

Note the isNull function in the code, which is used to judge whether the element exists. This method is actually based on whether the id of the element is null. The idea seems to be the same as using baseURI to judge. I tried to return true when the element exists.

But when the element does not exist, it will report an undefined error. Interested students can study it.

Summary:

In fact, it is simple and direct to judge whether an element exists by getElementById () (or other methods of selecting elements) combined with whether it is null, or to obtain an object by jQuery and judge its length.

But if you want to determine whether an element is in the current real-time visible dom, 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


Related articles: