Check presence of an element with jquery - javascript

I have a page in which i need to check the presence of a HTML element dynamically.Therefore I need to know the correct way of doing this

You could do:
$(function() {
if ($('.myElement').length > 0) {
console.log('There is one or more elements with class="myElement"');
}
});

$('#id').length === 0; // element does not exist
$('#id').length > 0; // element exists

Personally I like very much the "presence" idiom from Ruby on Rails, so I have added this to my JS set up:
jQuery.fn.presence = function presence() {
return this.length !== 0 ? this : null;
};
and now use this in my code:
if (el.presence()) { ... }
and better yet
const ul = el.parents('UL').first().presence() ?? el.siblings('UL').first()
(If you can't afford ??, || would do just as well here.)

Related

Checking if an element is present in the dom at the click of one button, if element is not present add it, else remove it [duplicate]

How do you test an element for existence without the use of the getElementById method?
I have set up 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 the above code demonstrates an element being stored into a variable and then removed from the DOM. Even though the element has been removed from the DOM, the variable retains the element as it was when first declared. 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.
PS: I'm also interested in why JavaScript variables behave like this if anyone knows of some good articles related to the subject.
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...
var elementExists = document.getElementById("find-me");
This is specified to either return a reference to the element or 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):
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.
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). That is, to use the contains() method on DOM elements.
You could use it like so...
document.body.contains(someReferenceToADomElement);
Use getElementById() if it's available.
Also, here's an easy way to do it with jQuery:
if ($('#elementId').length > 0) {
// Exists.
}
And if you can't use third-party libraries, just stick to base JavaScript:
var element = document.getElementById('elementId');
if (typeof(element) != 'undefined' && element != null)
{
// Exists.
}
Using the Node.contains DOM API, you can check for the presence of any element in the page (currently in the DOM) quite easily:
document.body.contains(YOUR_ELEMENT_HERE);
CROSS-BROWSER NOTE: the document object in Internet Explorer does not have a contains() method - to ensure cross-browser compatibility, use document.body.contains() instead.
I simply do:
if(document.getElementById("myElementId")){
alert("Element exists");
} else {
alert("Element does not exist");
}
It works for me and had no issues with it yet...
I prefer to use the node.isConnected property (Visit MDN).
Note: This will return true if the element is appended to a ShadowRoot as well, which might not be everyone's desired behaviour.
Example:
const element = document.createElement('div');
console.log(element.isConnected); // Returns false
document.body.append(element);
console.log(element.isConnected); // Returns true
Easiest way:
const cond = document.getElementById('elem') || false
if (cond) {
//does
} else {
//does not
}
If needed in strictly visible DOM, meaning not on entire page, use something like view-js (my lib so beat it up as much as you want)
<script src='https://view-js.glitch.me/view-main.js'></script>
<script>
elem = $sel('#myelem');
if (isVis(elem)) { //yes } else { //no }
</script>
function test() {
pt = document.querySelector('#result')
iv = document.querySelector('#f')
cond = document.querySelector('#'+iv.value) || false
if (cond) {
pt.innerText = 'Found!'
} else {
pt.innerText = 'Not found!'
}
}
Enter an id to see if it exists: <input id='f'></input>
<button onclick='test()'>Test!</button>
<br />
<p id='result'>I am a p tag. I will change depending on the result.</p>
<br />
<div id='demo'>I am a div. My id is demo.</div>
You could just check to see if the parentNode property is null.
That is,
if(!myElement.parentNode)
{
// The node is NOT in the DOM
}
else
{
// The element is in the DOM
}
From Mozilla Developer Network:
This function checks to see if an element is in the page's body. As contains() is inclusive and determining if the body contains itself isn't the intention of isInPage, this case explicitly returns false.
function isInPage(node) {
return (node === document.body) ? false : document.body.contains(node);
}
node is the node we want to check for in the <body>.
The easiest solution is to check the baseURI property, which is set only when the element is inserted in the DOM, and it reverts to an empty string when it is removed.
var div = document.querySelector('div');
// "div" is in the DOM, so should print a string
console.log(div.baseURI);
// Remove "div" from the DOM
document.body.removeChild(div);
// Should print an empty string
console.log(div.baseURI);
<div></div>
A simple way to check if an element exist can be done through one-line code of jQuery.
Here is the code below:
if ($('#elementId').length > 0) {
// Do stuff here if the element exists
} else {
// Do stuff here if the element does not exist
}
jQuery solution:
if ($('#elementId').length) {
// element exists, do something...
}
This worked for me using jQuery and did not require $('#elementId')[0] to be used.
csuwldcat's solution seems to be the best of the bunch, but a slight modification is needed to make it work correctly with an element that's in a different document than the JavaScript code is running in, such as an iframe:
YOUR_ELEMENT.ownerDocument.body.contains(YOUR_ELEMENT);
Note the use of the element's ownerDocument property, as opposed to just plain old document (which may or may not refer to the element's owner document).
torazaburo posted an even simpler method that also works with non-local elements, but unfortunately, it uses the baseURI property, which is not uniformly implemented across browsers at this time (I could only get it to work in the WebKit-based ones). I couldn't find any other element or node properties that could be used in a similar fashion, so I think for the time being the above solution is as good as it gets.
This code works for me, and I didn't have any issues with it.
if(document.getElementById("mySPAN")) {
// If the element exists, execute this code
alert("Element exists");
}
else {
// If the element does not exist execute this code
alert("Element does not exists");
}
Instead of iterating parents, you can just get the bounding rectangle which is all zeros when the element is detached from the DOM:
function isInDOM(element) {
if (!element)
return false;
var rect = element.getBoundingClientRect();
return (rect.top || rect.left || rect.height || rect.width)?true:false;
}
If you want to handle the edge case of a zero width and height element at zero top and zero left, you can double check by iterating parents till the document.body:
function isInDOM(element) {
if (!element)
return false;
var rect = element.getBoundingClientRect();
if (element.top || element.left || element.height || element.width)
return true;
while(element) {
if (element == document.body)
return true;
element = element.parentNode;
}
return false;
}
Another option is element.closest:
element.closest('body') === null
Use this command below to return whether or not the element exists in the DOM:
return !!document.getElementById('myElement');
Check element exist or not
const elementExists = document.getElementById("find-me");
if(elementExists){
console.log("have this element");
}else{
console.log("this element doesn't exist");
}
Check if the element is a child of <html> via Node::contains():
const div = document.createElement('div');
console.log(
document.documentElement.contains(div)
);//-> false
document.body.appendChild(div);
console.log(
document.documentElement.contains(div)
); //-> true
I've covered this and more in is-dom-detached.
You can also use jQuery.contains, which checks if an element is a descendant of another element. I passed in document as the parent element to search because any elements that exist on the page DOM are a descendant of document.
jQuery.contains( document, YOUR_ELEMENT)
A simple solution with jQuery:
$('body').find(yourElement)[0] != null
// This will work prefectly in all :D
function basedInDocument(el) {
// This function is used for checking if this element in the real DOM
while (el.parentElement != null) {
if (el.parentElement == document.body) {
return true;
}
el = el.parentElement; // For checking the parent of.
} // If the loop breaks, it will return false, meaning
// the element is not in the real DOM.
return false;
}
All existing elements have parentElement set, except the HTML element!
function elExists (e) {
return (e.nodeName === 'HTML' || e.parentElement !== null);
};
If an element is in the DOM, its parents should also be in
And the last grandparent should be the document
So to check that we just loop unto the element's parentNode tree until we reach the last grandparent
Use this:
/**
* #param {HTMLElement} element - The element to check
* #param {boolean} inBody - Checks if the element is in the body
* #return {boolean}
*/
var isInDOM = function(element, inBody) {
var _ = element, last;
while (_) {
last = _;
if (inBody && last === document.body) { break;}
_ = _.parentNode;
}
return inBody ? last === document.body : last === document;
};
this condition chick all cases.
function del() {
//chick if dom has this element
//if not true condition means null or undifind or false .
if (!document.querySelector("#ul_list ")===true){
// msg to user
alert("click btn load ");
// if console chick for you and show null clear console.
console.clear();
// the function will stop.
return false;
}
// if its true function will log delet .
console.log("delet");
}
As I landed up here due to the question. Few of the solutions from above don't solve the problem. After a few lookups, I found a solution on the internet that provided if a node is present in the current viewport where the answers I tried solves of it's present in the body or not.
function isInViewport(element) {
const rect = element.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
console.log(
isInViewport(document.querySelector('.selector-i-am-looking-for'))
);
<div class="selector-i-am-looking-for"></div>
The snippet is taken from HERE to keep as a backup as the links may be unavailable after some time. Check the link for an explanation.
And, didn't intend to post in the comment, as in most cases, they are ignored.
Use querySelectorAll with forEach,
document.querySelectorAll('.my-element').forEach((element) => {
element.classList.add('new-class');
});
as the opposite of:
const myElement = document.querySelector('.my-element');
if (myElement) {
element.classList.add('new-class');
}
I liked this approach:
var elem = document.getElementById('elementID');
if (elem)
do this
else
do that
Also
var elem = ((document.getElementById('elemID')) ? true:false);
if (elem)
do this
else
do that

Better way to do this via pure javascript

if(window.location.href.indexOf("=38805") > -1
|| window.location.href.indexOf("=38807") > -1
|| window.location.href.indexOf("=38816") > -1
|| window.location.href.indexOf("=38815") > -1
|| window.location.href.indexOf("=38814") > -1
|| window.location.href.indexOf("=38813") > -1
|| window.location.href.indexOf("=38811") > -1
){
do something
}
Basically, I am using a separate css for the pages that contain these strings. I might over 50 pages. Wondering if there is a cleaner way to write this. Put them into an array?
JS some function, is exactly for stuff like that:
let options = ["=38805","=38807","=38816"]; //...and the others
let link = window.location.href;
if( options.some( option => link.includes(option))){
console.log('yay! =)');
}
You're actually going through your array of options, and asking a question about each of the elements in the array : "Are you present at my URL?".
Then, the some method will return true (and in this case- active the if statment ) only if one or more elements in the options array is answering true to your includes question.
And by the way-
JS have another method that cover a similar set of mind. the every metohd.
This method, as you can understand by its name, will return true only if all the elements in the array is answering true to your question.
How about something like this to clean it up a bit:
const ids = [38805, 38807, 38811, 38813, 38814, 38815, 38816];
let windowHrefHasId = false;
for (let id of ids) {
if (window.location.href.indexOf('=' + id.toString()) > -1) {
windowHrefHasId = true;
break;
}
}
if (windowHrefHasId) {
// do something
}

How to check for attribute value

Please advise me if I am using correct syntax here for checking if “aria-expanded” is true for a particular set of elements with css class “classname”:
if ($(‘.classname’).hasAttribute('aria-expanded','true')) {
 output here
}
jQuery doesn't have a hasAttribute method, so I'm assuming $ = docuument.querySelector. (Note: not document.querySelectorAll; so, you're only considering a single element).
The hasAttribute method takes a single parameter: the name of the attribute you are checking for. To check that attribute's value, you'll need to use getAttribute and then compare that. So you might do:
if( $('.classname').getAttribute('aria-expanded') === 'true') {}
If you are using jQuery, then you can just use the attr method:
if ($('.classname').attr('aria-expanded') === 'true') {}
See also the MDN docs for hasAttribute.
If you're trying to check a set of elements, you could do something like this:
function allHaveAttribute(elements, attrName, attrValue) {
// First, check that all elements have the attribute
for (var i = 0; i < elements.length; i++) {
if (!elements[i].hasAttribute(attrName)) return false;
}
if (attrValue) { // if we're checking their value...
for (var i = 0; i < elements.length; i++) {
if (elements[i].getAttribute(attrName) !== attrValue)
return false;
}
return true;
} else { // we know all elements have the attribute
return true;
}
}
var els = document.querySelectorAll('.classname');
if (allHaveAttribute(els, 'aria-expanded', 'true') {
// action here
}
JSBin Example: http://jsbin.com/payaqijeqa/edit?js,console
jQuery doesn't have a .hasAttribute function
If it did, it would most likely only work on the first of the set
The following uses native JavaScript (ES5) to check that .every element in the set document.querySelectorAll('.classname') has that attribute set to true.
let allSet = [].every.call(document.querySelectorAll('.classname'), function(el) {
return el.getAttribute('aria-expanded') === 'true';
});
NB: the above test is case sensitive. It also ignore any elements that don't have that attribute at all. If the latter is an issue:
let allSet = [].every.call(document.querySelectorAll('.classname'), function(el) {
return el.hasAttribute('aria-expanded') && el.getAttribute('aria-expanded') === 'true';
});
You can check to see if every element with class "className" has the attribute "aria-expanded='true'" with:
if( $(".className").length === $(".className").filter("[aria-expanded='true']").length) {
//output here
}
CSS has attribute selectors that allow selection of elements with certain attributes. If you negate the selector (which is unique to jQuery), you can test if there are any elements that have the class but don't have the attribute value by using:
$(".className[aria-expanded!='true']").length == 0

can you use jquery to see if a target contains a <b> tag?

so, i have something like this.
var $list = $("div#item");
I was looking at :contains in the selector, but i wasnt sure if that applied to markup or if i should do something like:
if($list.find("<b>"))return 1;
else return 0;
Reasoning: Adding functionality to a program which uses inline tags, and want to maintain structure.
Goal: if(item contains an inline b, u, i tags) return 1; else return 0;
You can simplify it down to a single selector .find("b,i,u") and return the boolean comparison length > 0. If any of the tags <b><i><u> are found inside #item, the overall length will be > 0:
return $("#item").find("b,i,u").length > 0;
Proof of concept
Edit: If you really want a number zero or one back instead of the boolean, use a ternary:
return $("#item").find("b,i,u").length > 0 ? 1 : 0;
return document.querySelector("#item b, #item u, #item i") ? 1 : 0;
No need for jQuery.
If you need to support browsers IE7 and older, try this:
var elem = document.getElementById('item');
return elem.getElementsByTagName('b').length
+ elem.getElementsByTagName('i').length
+ elem.getElementsByTagName('u').length == 0 ? 0 : 1;
perhaps use the .has() method.
$('li').has('ul')
jquery has
you can also do that with .has() function
I'm not sure it's the most efficient, but I would use .find for this.
function hasInline(targetElement) {
return ($(targetElement).find('b,u,i').length > 0);
}
I'd also recommend expanding the function so you could specify whatever inline tags you wanted to check, like so:
// NOTE: This will return true if the element has ANY of the tags provided.
function hasInlineTags(targetElement, listOfTags) {
return ($(targetElement).find(listOfTags.join(',')).length > 0);
}
// Call it with whatever tags you want.
hasInlineTags($("div#item"), ['b','u','i']);
if you're using jQuery:
var styleElements = $('b,u,i', $list)
Use:
return (styleElements.length) ? 1 : 0;

How do I find if an element contains a specific class with jQuery?

I need to check if an element contains a certain child class using JQUERY.
I tried:
if ($('#myElement').has('.myClass')) {
do work son
}
Didn't work.
My html code is laid out like this:
<div id="myElement">
<img>
<span>something</span>
<span class="myClass">Hello</span>
</div>
The easiest way would be to search for .myClass as a child of #myElement:
if($('#myElement .myClass')).length > 0)
If you only want first level children, you'd use >
if($('#myElement > .myClass')).length > 0)
Another way would be passing a selector to find and checking for any results:
if($('#myElement').find('.myClass').length > 0)
Or for first level children only:
if($('#myElement').children('.myClass').length > 0)
Just use QS
var hasClass = document.getElementById("myElement").querySelector(".myClass");
or you could recurse over the children
var element = document.getElementById("myElement");
var hasClass = recursivelyWalk(element.childNodes, function hasClass(node) {
return node.classList.contains("myClass");
});
function recursivelyWalk(nodes, cb) {
for (var i = 0, len = nodes.length; i < len; i++) {
var node = nodes[i];
var ret = cb(node);
if (ret) {
return ret;
}
if (node.childNodes && node.childNodes.length) {
var ret = recursivelyWalk(node.childNodes, cb);
if (ret) {
return ret;
}
}
}
}
Using recursivelyWalk and .classList (which can be shimmed).
Alternatively you can use jQuery
$("#myElement .myClass").hasClass("myClass");
or if you want composite operations without jQuery then try NodeComposite
NodeComposite.$("#myElement *").classList.contains("myClass");
Try:
if($('#myElement').children('.myClass').length) {
// Do what you need to
}
The jQuery object returns an array, which has the .length property. The above code checks if there are any .myClass children in #myElement and, if there are (when .length isn't 0), executes the code inside the if() statement.
Here's a more explicit version:
if($('#myElement').children('.myClass').length > 0) {
// Do what you need to
}
You could always use $('#myElement .myClass').length too, but $.children() is clearer to some. To find elements that aren't direct children, use $.find() in place of $.children().
if($.contains($('#myElement'), $('.myClass'))){
alert("True");
}
else{alert("False")};

Categories