Change all childs id of a div element - javascript

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";

Related

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

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)

set value of element

I want to create a new element and then set the value of the new element. Then add the element to div.
var x = document.getElementById("Header");
var element =document.createElement("test");
var addel=x.appendChild(element)
<div id="Header">
<h1>
<img height="150" src="http://test.com/im.jpeg">
<span>test</span>
</h1>
</div>
for instance, create a new element called "test" then add the element to div and set the value of test="1".
Your new element won't be recognised by the browser as html has fixed set of elements
You perhaps need to use a text based element like span,p or you can simply set innerText of a block element like div to "1"
If you want to create your own elements You can refer here
https://developers.google.com/web/fundamentals/web-components/customelements
You can also extend existing elements to form new elements
You can use Node.textContent or HTMLElement.innerText property to set the text:
var x = document.getElementById("Header");
var element =document.createElement("test");
element.textContent = "1";
var addel=x.appendChild(element);
<div id="Header">
<h1>
<img height="150" src="http://test.com/im.jpeg">
<span>test</span>
</h1>
</div>
change the code with
var x = document.getElementById("Header");
var element =document.createElement("test");
element.setAttribute('value','1');
var addel=x.appendChild(element);

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.

Update DOM reference in jQuery each

I am modifying an elements innerHTML property inside a $.each() loop. Now if my stack of elements contains childrens of the element where I update the innerHTML, the DOM reference of that children will get lost.
Example:
$(function(){
$stack = $(".myelement, .myelement *");
$stack.each(function(){
var $this = $(this);
var element = $(this)[0];
console.log(element.innerHTML = element.innerHTML + " modified");
});
});
Fiddle: https://jsfiddle.net/b0ux0v5e/
What happens is that I first modify the innerHTML of .myelement. This includes the children p. Therefore the DOM reference of this element is get lost and "modified" will not be appended.
How can such an scenario be solved without building a function that creates a unique selector for the element and re-catches it in each loop?
Note: I am not asking for specifically appending some text to nodes. This is just an example. In a real project I am replacing text in the innerHTML.
I guess you want to modify the text content. in this case you would like to know about .contents() method, which lets you loop through with text nodes as well:
$(function() {
$(".myelement").contents().each(function(i, el) {
el.textContent += " 'modified'";
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myelement">
I am the myelement
<p>
Hello world
</p></div>
Don't modify innerHTML, it will destroy/recreate all the elements inside and force a re-render. You can use insertAdjacentHTML or jQuery's append to add to an element.
Also you do not need to do:
element = $(this)[0];
this will already be a reference to the element.
$(function(){
$stack = $(".myelement, .myelement *");
$stack.each(function(){
var $this = $(this);
//this.insertAdjacentHTML("beforeend"," modified");
//Or
$this.append(" modified");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="myelement">
<span>A span</span>
<div>A div</div>
<div>
<p>a paragraph in a div</p>
</div>
</div>
EDIT
As it seems you want to replace word(s) and not append a word, you could do a replace on the html and then reset it, but again this will destroy/recreate the elements inside, so if any of them have something like event listeners attached they will be lost
var modified = $".myelement").html().replace(/yourword/g,"modified");
$(".myelement").html(modified);
Or you could just loop over all the Text nodes and replace the word from there, this will keep the elements, their event listeners, and so on intact.
$(".myelement, .myelement *").contents().filter(function() {
return this.nodeType == 3;
}).each(function(){
this.textContent = this.textContent.replace(/A/g,"modified");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="myelement">
Inside A element <br>
<span>A span</span>
<div>A div</div>
<div>
<p>a paragraph in A div</p>
</div>
</div>
just change
$stack = $(".myelement, .myelement *");
to
$stack = $(".myelement");
And you will see in your console
I am the myelement
<p>
Hello world
</p> modified

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>

Categories

Resources