How can I check if an element still exists in the DOM? - javascript

How can I check if an element still exists in the DOM?
<div id="parent">
...
<div class="my-class"></div>
</div>
let parent = document.getElementById('parent');
let myElement = parent.getElementsByClassName('my-class')[0];
parent.remove();
function stillExists(element) {
// check if element still exists in DOM
}
stillExists(myElement) // should be false

Simply do
document.contains(myElement)

Related

getElementById from ancestor element to remove child's class

I want to use a parent element with getElementById.
For example: I want to use ancestor id "test" to remove class "myClass".
HTML
<div id="test">
<div id="test-child-one">
...
</div>
<div id="test-child-two">
...
</div>
<div id="test-child-three">
<div class="myClass"></div>
</div>
</div>
Javascript
var element = document.getElementById("test");
element.className = element.className.replace(/\bmyClass\b/g, "");
It won't work. Please help! Thanks.
You could do this:
//If you want to remove the class from all decendants
//Get all decendants with class "myClass"
const childEles = document.getElementById('test').querySelectorAll('.myClass');
//Or per David
const childEles = document.querySelectorAll('#test .myClass');
//Iterate the collection and remove "myClass" from all decendants
for(let x = 0; x < childEles.length; x++){
childEles[x].classList.remove("myClass");
}
//If you only want to remove the first decendant
document.getElementById('test').querySelectorAll('.myClass')[0].classList.remove("myClass");
//Or per David
document.querySelectorAll('#test .myClass')[0].classList.remove("myClass);
Do like Ryan Wilson specified it or simple one-liner:
document.getElementById("test").querySelectorAll('.myClass').forEach(function (el) { el.classList.remove("myClass"); });
Or a beautiful way, if you have transpiler between your code and browser:
removeChildrenClass = (parentId, childClass) => document.querySelectorAll(`#${parentId} .${childClass}`).forEach(el => el.classList.remove(childClass));
removeChildrenClass("test", "myClass");
Expanding on the other answers provided, it seems as though you are looking for querySelectorAll. Given that you already have some ancestor element element, querySelectorAll can be used to find all children with the specified class. To build on your example:
Using querySelectorAll
// Example constant element IDs/classes
var parentId = "test";
var targetClass = "myClass";
// The given parent element
var element = document.getElementById(parentId);
// Iterate over all children `elem`s with the target class
element.querySelectorAll(targetClass).forEach(function (elem) {
elem.classList.remove(targetClass);
});
This is just an example to demonstrate how querySelectorAll can be used on specific elements to solve exactly such a problem. Note that querySelectorAll will match multiple classes containing myClass if they exist, if you want to specifically remove the first such class, you might use querySelector instead.

can't append to jQuery wrap

Why can't you append to an element that you use to wrap another - see example below?
var $test = $('.test'),
$test1 = $('.test1'),
$move = $('.move'),
$testWrapper = $('<div class="test-wrapper"></div>'),
$test1Wrapper = $('<div class="test1-wrapper"></div>');
$test.wrap($testWrapper);
// move item and return to wrapper
$move.append($test);
$testWrapper.append($test); // this is the line that does not work?
console.log($testWrapper); // still seems to be a jquery object?
$test1.after($test1Wrapper); // if you place the element after instead of using it to wrap, then it works?
$move.append($test1);
$test1Wrapper.append($test1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">test</div>
<div class="test1">test 1</div>
<div class="move"></div>
wrap() seems to clone the markup of the provided element for wrapping, not the actual element itself. You can see it in the developer tools when you use console.log($testWrapper) and hover over that line in your browser console: normally, the DOM element should be highlighted, but it's not. So what is referenced by the variable $testWrapper after wrapping is still (a jQuery collection of) a node that is not attatched to the DOM.
var $test = $('.test'),
$test1 = $('.test1'),
$move = $('.move'),
$testWrapper = $('<div class="test-wrapper"></div>');
$test.wrap($testWrapper);
// move item and return to wrapper
$move.append($test);
console.log($testWrapper); // <= if you hover this element in the browser console, it doesn't highlight the actual DOM element either; that's how you can visully detect that it's not the same element!
$testWrapper = $('.test-wrapper'); // select the actual DOM element that has been created for wrapping
$testWrapper.append($test); // now it will work!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">test</div>
<div class="move"></div>

firstChild node issue for DOM traversal in Javascript

Building this basic to-do list from scratch to try and teach myself Javascript. I found out through the API that there is a firstChild function that will target the first child of a parent node.
If I have..
<div class = "parentNode">
<div id = "i0">
TEXT HERE
</div>
<div id = "i1">
</div>
</div>
Then I have some button that is designated to the function:
document.getElementById('myButton').onclick = function () {
var parentNode = document.getElementById('parentNode');
var childNode = parentNode.firstChild.innerHTML;
alert('childNode');
}
Why would this not return TEXT HERE in the alert box?
There are a few things going on here. First, you are looking for an element that does not exist
var parentNode = document.getElementById('parentNode');
is looking for an id. This can be remedied by using an id="parentNode on the element, or you can query by class name instead using querySelectorMDN
var parentNode = document.querySelector('.parentNode');
Next, alert('childNode'); will always alert the string "childNode" and not the variable childNode so that needs to be alert(childNode).
Lastly, and perhaps most interesting, is that .firstChild will get the first childNode of the set of childNodes. This can be a #text node (which it is), becuase of the whitespace used between the end of the <div class = "parentNode"> and the beginning of <div id = "i0">.
As opposed to using .firstChild, you can use children[0] which will only look at elements. Here is a snippet that shows this behavior.
document.getElementById('myButton').onclick = function () {
var parentNode = document.querySelector('.parentNode');
var childNode = parentNode.children[0].innerHTML;
alert(childNode);
}
<button id="myButton" type="button">Click To Check Node</button>
<div class = "parentNode">
<div id = "i0">
TEXT HERE
</div>
<div id = "i1">
</div>
</div>

Change all childs id of a div element

Following my code:
HTML:
<div id="element">
<div></div>
<div id="c_a"></div>
<div></div>
<div id="c_b"></div>
</div>
Javascript:
var element = document.getElementById("element");
var clone_element = element.cloneNode(true);
How to change the name of all the id (including the "element") of the variable clone_element?
You can get the child divs of div#element using clone_element.getElementsByTagName('div'); and loop through them, changing the id property of each as needed.
Here is a reference to some DOM object properties.
You can set the id of the cloned element directly.
clone_element.id = "new_element_id";
The children can be accessed using the children property:
clone_element.children[1].id = "clone_a";
clone_element.children[3].id = "clone_b";

get value of child <div> of a parent <div>

<div id="parent">
<div id="child">
some-value
</div>
</div>
how do I get "some-value"?
I tried
var parent = document.getElementById("parent");
var child = parent.childNodes[0];
var childval = child.value;
document.getElementById("output").innerHTML=childval;
it outputs "undefined".
The value property only exists for form elements. If you want to get the content of any other elements, you can either use innerHTML [MDN] to get the content as HTML string, or textContent [MDN] resp. innerText [MSDN] to only get the text content without HTML tags.
childNodes [MDN] returns all child nodes, not only element nodes. That means, it also contains text nodes for example. The line break you have after <div id="parent"> is a text node as well. Hence, parent.childNodes[0] returns the text node which consists only of a line break.
If you want to get the first element node, you can either use children [MDN] (see browser compatibility), or iterate over the child nodes, testing what kind of node each of them is. 1 indicates an element node, 3 a text node:
var child = parent.firstChild;
while(child && child.nodeType !== 1) {
child = child.nextSibling;
}
There are also other ways to retrieve elements, e.g. with getElementsByTagName [MDN].
Or in your case, you can just use getElementById [MDN] to get a reference to both of the elements.
The problem is that parent <div> actuially has three children: a TextNode containing a new line after parent opening tag, the actual child <div> and yet another TextNode with newline after closing child tag. But hard-coding second item is a bad idea:
var parent = document.getElementById("parent");
console.info(parent.childNodes.length);
var child = parent.childNodes[1];
var childval = child.innerHTML;
I would suggest iterating over children and finding the actual child or using
parent.getElementsByTagName('div')
shorthand.
That's one of the reasons why people love jQuery so much:
$('#parent div').text()
var parent = document.getElementById("parent");
var child = parent.children[0];
var childVal = child.innerHTML;
document.getElementById("output").innerHTML = childVal;
DEMO : http://jsfiddle.net/bcqVC/2/
document.getElementById("output").innerHTML = document.getElementById("child").innerHTML;
This will solve your problem.
Using your way of approach try as shown below
var parent = document.getElementById("parent");
var child = parent.childNodes[0];
var childval = child.innerHTML;
document.getElementById("outPut").innerHTML=childval;
This will also solve your problem
To get all the <div> elements you can use:
var div_val=prompt("Enter a div to Get the Child Elements","");
var div_ele=document.getElementById(div_val).childNodes;
for (var i=0, max=div_ele.length; i < max; i++) {
alert(div_ele[i]); //All your Div Elements
}
try this way by this pointer.
var childs = document.getElementById('myDropdown').children; //returns a HTMLCollection
for (var indx = 0; indx < childs.length; indx++) {
// iterate over it
childs[indx].onclick = function() {
// attach event listener On Symbole Dive THIS .
this.style.color = "#ff0000";
// add to note form the symbole .
document.getElementById("Note_form").value += this.innerHTML;
}
}
<div class="dropdown">
<div id="myDropdown" class="dropdown-content">
<div>♥</div>
<div>☺</div>
<div>π</div>
<div>•</div>
<div>Σ</div>
<div>°</div>
<div>Ω</div>
<div>∞</div>
<div>×</div>
<div>÷</div>
<div>≥</div>
<div>≤</div>
<div>≠</div>
<div>®</div>
<div>©</div>
<div>¥</div>
<div>£</div>
<div>€</div>
</div>
</div>
<textarea id="Note_form" class="copy_erea" placeholder="The Content.." oninput="note_Edite(this.value);"></textarea>

Categories

Resources