Check if a DOM element node actually exists in DOM [duplicate] - javascript

This question already has answers here:
HTML element is attached to a document
(5 answers)
Closed 8 months ago.
I'm defining a function that should receive a DOM element node as a parameter.
There is any efficient way to validate if the element node received actually exists in the DOM?
For example if the element node received has been created through Document.createElement() but not appended to the DOM, I want the validation fails.
I already accomplished it with the code below, but I'm afraid that checking for all DOM element nodes is not the best solution for performance.
function checkIfNodeExists(nodeElement) {
return [...document.querySelectorAll("*")].includes(nodeElement);
}
Could someone suggest a better solution or convince me that my solution is already appropriate?

You want to check if an element is in the DOM? You can see if it is in the body.
var div1 = document.createElement("div");
var div2 = document.querySelector("#foo");
console.log(document.body.contains(div1))
console.log(document.body.contains(div2))
<div id="foo"><div>

Related

Vanilla JS - Is it performant to use const instead of getElementById etc? [duplicate]

This question already has answers here:
Caching DOM elements
(1 answer)
Caching vs .querySelector [closed]
(1 answer)
Closed 2 years ago.
I know in jQuery it is best practice to assign selectors to variables in order to prevent from traversing the DOM repeatedly.
Is this also the case in vanilla JS, or do the extra lines declaring the constants just take up space unnecessarily?
jQuery Version:
var elem = $('#elem');
Vanilla JS Equivalent
const elem = document.getElementById('elem');
short answer: yes
getElementById is a function, every time you call it, it will traverse the DOM tree to find that element. You are essentially caching those results by storing it in a variable.

is there a way that an object will know that it was added to the DOM? [duplicate]

This question already has answers here:
Detect changes in the DOM
(11 answers)
Closed 5 years ago.
In my app, I create many dynamically objects. some of them needs to be initialized AFTER they are added to the DOM.
I want them to be "smart" and execute some code only when they are added to the dom.
o/c - i can execute the code manually, after insertion. but i am trying to avoid it.
can it be done?
how?
You can add your prototype wrap for method .appendChild or use MutationEvents
Node.prototype.myAppend = function (el) {
this.appendChild(el);
el.onAppend && el.onAppend.call && el.onAppend();
}
var div = document.createElement('div');
// handler after append in DOM
div.onAppend = function () {
alert('Node added in DOM');
}
document.body.myAppend(div);

Getting div by class name and returning it in javascript [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 7 years ago.
I am trying to inject some javascript into a web page using a very simple js script:
var c = document.getElementsByClassName("main").innerHTML;
alert(c);
I want to set an alert of the text (and only the text) in the div with class="main". Currently the script is making an alert pop up saying 'undefined'. What am I doing wrong, the class name is definitely correct, and I have searched stackoverflow and other sources, having experimented with .innerHTML and .textContent but nothing seems to be able to simply return a var of text.
getElementsByClassName returns an array like object. There is no innerHTML property on it. You need to either act on all the divs returned or a specific one. See docs for further examples. https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
document.getElementsByClassName returns an array because there could be multiple classes with the same class name.
Try doing
var c = document.getElementsByClassName("main")[0].innerHTML;
alert(c);
The issue is that you are returning a set of nodes (HTMLCollection). All elements with the class "main" (getElementsByClassName). For example, this will show you the first element's innerHTML
var c = document.getElementsByClassName("main")[0].innerHTML;
alert(c);
However, a more standardized approach for this would be to use querySelector like this
var c = document.querySelector(".main").innerHTML;
alert(c);
With getElementsByClassName() it returns an array(in this case a group of elements) which you have to define an offset to mark which one of the elements you want to use:
document.getElementsByClassName("main")[0].innerHTML;//0 returns the first element
JSFiddle Demo
If you want to select all the elements of the class, the easiest way is to use a loop:
var element =document.getElementsByClassName("main");
for($i=0;$i<=element.length;$i++){
alert(element[$i].innerHTML);
}
JSFiddle Demo

why does this script only give half the output? [duplicate]

This question already has answers here:
javascript document.write() removes the html from page and display result in a blank page [duplicate]
(3 answers)
Closed 10 years ago.
Here is the function:
function funct1()
{
document.getElementById("demo").innerHTML="Something";
document.write("Mexico!");
}
The output is only:
Mexico
when I click the button on the page, whereas I wanted the output to be:
Something
Mexico
In this instance document.write() doesn't do what you think. It clears the contents of the document, and writes Mexico! (see Quentin's answer for a more detailed explanation of why that is). If you remove this line, you can see that your first statement is executed correctly.
If you want to update the first paragraph, and also add another, you should use the following code:
function funct1()
{
document.getElementById("demo").innerHTML = "Something";
// Create a new <p> element, set its HTML and then append it:
var newP = document.createElement('p');
newP.innerHTML = 'Mexico!';
document.body.appendChild(newP);
}
You can see a working jsFiddle here.
After setting the innerHTML of demo, you call document.write. Since the document is in a closed state at this time, this makes an implicit call to document.open which erases the entire existing document (including the stuff you just assigned with innerHTML). Then you write Mexico! to the new document.
Never call document.write after the DOM is ready (and avoid doing so at any other time). Use DOM manipulation instead.

Access a DOM element by using its id as var [duplicate]

This question already has answers here:
Do DOM tree elements with IDs become global properties?
(5 answers)
Closed 8 years ago.
I just came across this by accident and I want to check if this is actually supposed to happen.
I have a div in my page with id box. In my Javascript I set a style to a variable named box: box.style.webkitTransform = "yadda yadda".
I thought that box was in scope, declared as var box = document.getElementById('box');, but it is not (the declaration is in another function!). Neither is there a var box defined globally or in any other place.
However the style got assigned just fine. So somehow the elements' id can be used globally in Javascript? Convenient, but I'm afraid to use it. I assume if the name is used for an actual variable it will override this behavior.
Some browsers add 'named elements' as properties of the document or windowobject. See this SO-question, especially the excellent answers from bobince

Categories