Is there a way to test a css-selector query to an unappended element? - javascript

I have this code:
Element.prototype.queryTest = function(strQuery) {
var _r;
if (this.parentElement == null) {
_r = Array.prototype.slice.call(document.querySelectorAll(strQuery)).indexOf(this);
} else {
_r = Array.prototype.slice.call(this.parentElement.querySelectorAll(strQuery)).indexOf(this);
}
return !!(_r+1);
}
I am searching for some way to test a query to an unappended element.
I want to change the first code to make this work:
var t = document.createElement("span");
t.classList.add("asdfg");
console.log(t.queryTest("span.adsfg"));
If there is a way to detect if the element isn't appended I could create a new temporary unappended one and append the target one to the temporary one to test the css-selector query.
Is there a way to detect if the element hasn't been appended jet? Could the target element be accessible even after freeing the temporary parent one? I have tested it on Chrome and it is accessible but I don't know if that is the case for firefox.
I know I can use document.querySelectorAll("*") to get a list of nodes but... isn't too CPU-demmanding the process to turn this NodeList to an Array? This is why I prefer not to use that way.
Thanks in advance.

There is already a native Element.prototype.matches method which does that:
const el = document.createElement('span');
el.classList.add('test');
console.log(el.matches('span.test'));
Note that to check if a node is connected or not, there is the Node.prototype.isConnected getter.

I did it.
Element.prototype.querySelectorTest = function(strQuery) {
var _r;
if (this.parentElement != null) {
_r = Array.prototype.indexOf.call(this.parentElement.querySelectorAll(strQuery),this);
} else if (this == document.documentElement) {
_r = ((document.querySelector(strQuery) == this)-1);
} else {
_r = ((this == document.createElement("i").appendChild(this).parentElement.querySelector(strQuery))-1);
}
return !!(_r+1);
}
I changed the way it check the nodeList.
I renamed the function to a more proper name.
If the target element is the root one there's no need to make a querySelectorAll.
If you append the unappended element to a temporary one to test the child you don't loose the reference (variable value in case there is one).
This is not my native language so please consider that.

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

How to compare if an HTML element exists in the node array?

selectedContentWrap: HTML nodes.
htmlVarTag: is an string.
How do I check if the HTML element exists in the nodes?
The htmlVarTag is a string and don't understand how to convert it so it check again if there is a tag like that so that if there is I can remove it?
here is output of my nodes that is stored in selectedContentWrap
var checkingElement = $scope.checkIfHTMLinside(selectedContentWrap,htmlVarTag );
$scope.checkIfHTMLinside = function(selectedContentWrap,htmlVarTag){
var node = htmlVarTag.parentNode;
while (node != null) {
if (node == selectedContentWrap) {
return true;
}
node = node.parentNode;
}
return false;
}
Well if you could paste the content of selectedContentWrap I would be able to test this code, but I think this would work
// Code goes here
var checkIfHTMLinside = function(selectedContentWrap,htmlVarTag){
for (item of selectedContentWrap) {
if (item.nodeName.toLowerCase() == htmlVarTag.toLowerCase()){
return true;
}
}
return false;
}
Simplest is use angular.element which is a subset of jQuery compatible methods
$scope.checkIfHTMLinside = function(selectedContentWrap,htmlVarTag){
// use filter() on array and return filtered array length as boolean
return selectedContentWrap.filter(function(str){
// return length of tag collection found as boolean
return angular.element('<div>').append(str).find(htmlVarTag).length
}).length;
});
Still not 100% clear if objective is only to look for a specific tag or any tags (ie differentiate from text only)
Or as casually mentioned to actually remove the tag
If you want to remove the tag it's not clear if you simply want to unwrap it or remove it's content also ... both easily achieved using angular.element
Try using: node.innerHTML and checking against that
is it me or post a question on stackoverflow and 20min after test testing I figure it.,...
the answer is that in the selectedContentWrap I already got list of nodes, all I need to do i compare , so a simple if for loop will fit.
To compare the names I just need to use .nodeName as that works cross browser ( correct me if I am wrong)
Some dev say that "dictionary of tag names and anonymous closures instead" - but couldn't find anything. If anyone has this library could you please post it to the question?
here is my code.
var node = selectedContentWrap;
console.log('node that is selectedwrapper', selectedContentWrap)
for (var i = 0; i < selectedContentWrap.length; i++) {
console.log('tag name is ',selectedContentWrap[i].nodeName);
var temptagname = selectedContentWrap[i].nodeName; // for debugging
if(selectedContentWrap[i].nodeName == 'B' ){
console.log('contains element B');
}
}

How to make my css selector engine more flexible?

I created a custom css selector engine function for my custom javascript library like so,
var catchEl = function(el) { // Catching elements by identifying the first character of a string
var firstChar = el[0],
actualNode = el.substring(1, el.length),
elements,
tempElems = [];
if (!document.querySelectorAll) {
try{
if(firstChar === "#") {//So, we can look for ids
tempElems.push(document.getElementById(actualNode));
} else if(firstChar === ".") {//or classes
elements = document.getElementsByClassName(actualNode);
for(i=0;i<elements.length;i++) tempElems.push(elements[i]);
} else {//or tags
elements = document.getElementsByTagName(el);
for(i=0;i<elements.length;i++) tempElems.push(elements[i]);
}
} catch(e) {};
} else {//but before everything we must check if the best function is available
try{
elements = document.querySelectorAll(el);
for(i=0;i<elements.length;i++) tempElems.push(elements[i]);
} catch(e) {};
}
return tempElems;
}
This function returns an array of elements. However, I turned my head around and tried to make it more flexible so that it can also return the window, document or this object, but was unsuccessful. Whenever I try to push the window object into the tempElems array, the array is still empty.
So, I want to know how to make this function return an array of elements when a string is passed through it or return the respective objects(window, document or this) as desired.
Note: I don't want to work with jQuery. So, please don't post any answers regarding jQuery.

Is it possible to get element's numerical index in its parent node without looping?

Normally I'm doing it this way:
for(i=0;i<elem.parentNode.length;i++) {
if (elem.parentNode[i] == elem) //.... etc.. etc...
}
function getChildIndex(node) {
return Array.prototype.indexOf.call(node.parentNode.childNodes, node);
}
This seems to work in Opera 11, Firefox 4, Chromium 10. Other browsers untested. It will throw TypeError if node has no parent (add a check for node.parentNode !== undefined if you care about that case).
Of course, Array.prototype.indexOf does still loop, just within the function call. It's impossible to do this without looping.
Note: If you want to obtain the index of a child Element, you can modify the function above by changing childNodes to children.
function getChildElementIndex(node) {
return Array.prototype.indexOf.call(node.parentNode.children, node);
}
Option #1
You can use the Array.from() method to convert an HTMLCollection of elements to an array. From there, you can use the native .indexOf() method in order to get the index:
function getElementIndex (element) {
return Array.from(element.parentNode.children).indexOf(element);
}
If you want the node index (as oppose to the element's index), then replace the children property with the childNodes property:
function getNodeIndex (element) {
return Array.from(element.parentNode.childNodes).indexOf(element);
}
Option #2
You can use the .call() method to invoke the array type's native .indexOf() method. This is how the .index() method is implemented in jQuery if you look at the source code.
function getElementIndex(element) {
return [].indexOf.call(element.parentNode.children, element);
}
Likewise, using the childNodes property in place of the children property:
function getNodeIndex (element) {
return [].indexOf.call(element.parentNode.childNodes, element);
}
Option #3
You can also use the spread operator:
function getElementIndex (element) {
return [...element.parentNode.children].indexOf(element);
}
function getNodeIndex (element) {
return [...element.parentNode.childNodes].indexOf(element);
}
You could count siblings...
The childNodes list includes text and element nodes-
function whichChild(elem){
var i= 0;
while((elem=elem.previousSibling)!=null) ++i;
return i;
}
There is no way to get the index of a node within its parent without looping in some manner, be that a for-loop, an Array method like indexOf or forEach, or something else. An index-of operation in the DOM is linear-time, not constant-time.
More generally, if list mutations are possible (and the DOM certainly supports mutation), it's generally impossible to provide an index-of operation that runs in constant time. There are two common implementation tactics: linked lists (usually doubly) and arrays. Finding an index using a linked list requires a walk. Finding an index using an array requires a scan. Some engines will cache indexes to reduce time needed to compute node.childNodes[i], but this won't help you if you're searching for a node. Not asking the question is the best policy.
I think you've got it, but:
make sure that variable "i" is declared with var
use === instead of == in the comparison
If you have a collection input elements with the same name (like <textarea name="text_field[]"…) in your form and you want to get the exact numeric index of the field that triggered an event:
function getElementIdxFromName(elem, parent) {
var elms = parent[elem.name];
var i = 0;
if (elms.length === undefined) // there is only one element with this name in the document
return 0;
while((elem!=elms[i])) i++;
return i;
}
Getting numeric id of an element from a collection of elements with the same class name:
function getElementIdxFromClass(elem, cl) {
var elems = document.getElementsByClassName(cl);
var i = 0;
if (elems.length > 0) {
while((elem!=elems[i])) i++;
return i;
}
return 0;
}
Try this:
let element = document.getElementById("your-element-id");
let indexInParent = Array.prototype.slice.call(element.parentNode.parentNode.children).indexOf(element.parentNode));

How might I determine the XPath of a DOM element?

In JavaScript, supposing I have a reference to an element, how do I retrieve an XPath expression that would select it?
Is there something like objElement.xpath?
Since Annibigi doesn't want to post the solution, I'll do it: See this snippet.
This is not XPATH related, but just to show you how you can get the parent/child relationship with a damn simple while loop.
var pathAt = function(node) {
var stack = [];
while(node.parentNode !== null) {
stack.unshift(node.tagName);
node = node.parentNode;
}
return stack.join('/');
}
// Usage : pathAt(document.getElementBy('moo'));
// Outputs : "HTML/BODY/CENTER/TABLE/TBODY/TR/TD/TABLE/TBODY/TR/TD/TABLE/TBODY/TR/TD/TABLE/TBODY/TR/TD"

Categories