How to auto generate id for child div in JQuery - javascript

How to auto generate id for child div in JQuery. Please help me so can i solve problem.
there is html code i want to set ids for these so can i apply operation on these.
<div id="main">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
I want to fit this. when click on + it should be max on complete div and when less it should be again on same possition.

If you try to create new div and assign it to it one possible solution may be:
<div id="parent">
</div>
for(var i = 0; i< 10; i++) { // suppose I append 10 divs to parent
$('#parent')
.append('<div id="myid_'+ i +'">child'+ i +'</div>');
}
DEMO
But if you've already child divs within parent then
<div id="parent">
<div>child 1</div>
<div>child 2</div>
<div>child 3</div>
</div>
then one possible approach would be
$('#parent div').each(function(i) {
$(this).attr('id', 'myid_' + i);
});
According to edit
<div id="main">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
$('#main .child').each(function(i) {
$(this).attr('id', 'myid_' + i);
});
DEMO
Another approach would be
$('#main .child').attr('id', function(i) {
return 'myid_' + i;
});
DEMO

There is no ways to do it automatically because live() call does not support ready event

This will give the child div's ID like child-1,child-2 etc... child-n
$(function(){
var childDivs=$("#main div");
for(var i=0;i<childDivs.length;i++)
{
$(childDivs[i]).attr("id","child-"+i);
}
});
Example : http://jsfiddle.net/nsQcR/12/
(You can check the view source to see the ID's);

To follow on to thecodeparadox's response for creating new div and assigning values, if you'd like the id and other info to be taken from a hash within an array:
arry = [{name: name1, addr: addr1, id: id1}, {name: name2, addr: addr2, id: id2}, etc...]
<div id="parent">
</div>
for(var i = 0, l = arry.length; i < l; i++) {
var obj = arry[i]
name = obj.name
pid = obj.pid
addr = obj.addr
$('#parent').append('<div id=' + pid + '>' + name + ': ' + addr + '</div>');
};

Related

Hide parent div when it contains <textarea>?

I have got a div structure that is dynamically generated by it's content. It is looking like this:
<div class="fpd-list-row fpd-add-layer" id="1609962837979"><div class="fpd-cell-0"><span></span></div><div class="fpd-cell-1">Dein Foto</div><div class="fpd-cell-2"><span class="fpd-icon-add"></span></div></div>
<div class="fpd-list-row" id="1609962838288"><div class="fpd-cell-0"><span class="fpd-current-color" style="background: #ffffff" data-colors=""></span></div><div class="fpd-cell-1"><textarea>Wanderlust</textarea></div><div class="fpd-cell-2"><span class="fpd-lock-element"><span class="fpd-icon-unlocked"></span></span></div></div>
I want to hide only the textareas and the parents element up to .fpd-list-row but keep the other div like .fpd-list-row .fpd-add-layer untouched. When I set the textarea to display none, the parent divs still exists. Is there a way hide the parent div up to ..fpd-list-row only when it contains <textarea>?
Loop through all divs, and use .find() to check for parent elements matching a certain selector.
$(document).ready(function(){
var divs = $("div");
for(var i = 0; i < divs.length; i++){
var current = divs[i];
if($(current).find("textarea").length != 0){
current.style.display='none';
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fpd-cell-1"><textarea>My Text</textarea></div>
<div class="fpd-cell-2"><span class="fpd-lock-element">fpd-lock-element<span class="fpd-icon-unlocked">fpd-icon-unlocked</span></span></div>
<div class="fpd-cell-3"><textarea>My Text</textarea></div>
For the most concise solution (one liner), use:
$(document).ready(function(){
jQuery('textarea').parent().hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fpd-cell-1"><textarea>My Text</textarea></div>
<div class="fpd-cell-2"><span class="fpd-lock-element">fpd-lock-element<span class="fpd-icon-unlocked">fpd-icon-unlocked</span></span></div>
<div class="fpd-cell-3"><textarea>My Text</textarea></div>
Check the children of the parent div:
divs = document.getElementsByTagName("DIV")
for (var i = 0; i < divs.length; i++) {
if (divs[i].childElementCount == 1 && divs[i].children[0].tagName.toLowerCase() == "textarea") {
divs[i].style.display = "none";
}
else { //for demonstration purposes
divs[i].style.backgroundColor="red"
}
}
<div class="fpd-cell-1"><textarea>My Text</textarea></div>
<div class="fpd-cell-2"><span class="fpd-lock-element">Outer Span<span class="fpd-icon-unlocked">Inner Span</span></span>
</div>
<div class="fpd-cell-3"><textarea>My Text</textarea></div>
Or, remove the parent of the textarea (idea credit of Spectric):
textareas = document.getElementsByTagName("TEXTAREA")
for (var i = 0; i < textareas.length; i++) {
textareas[i].parentNode.style.display = "none"
}
<div class="fpd-cell-1"><textarea>My Text</textarea></div>
<div class="fpd-cell-2"><span class="fpd-lock-element">Outer Span<span class="fpd-icon-unlocked">Inner Span</span></span>
</div>
<div class="fpd-cell-3"><textarea>My Text</textarea></div>
The first example hides the div only if there is one element in it, and it is the textarea, whereas the second method hides the parent of the textarea. Therefore, the first one can be used in situations where you need a textarea, and the second one just won't show any textareas regardless of the situation.
However, you could just make the dynamic content not generate the textarea and use a div:blank pseudo class in the css.
--------------- UPDATE ---------------
Update after code was updated in question.
textareas = document.getElementsByTagName("TEXTAREA")
for (var i = 0; i < textareas.length; i++) {
textareas[i].parentNode.parentNode.style.display = "none"
}
<div class="fpd-list-row fpd-add-layer" id="1609962837979">
<div class="fpd-cell-0"><span></span></div>
<div class="fpd-cell-1">Dein Foto</div>
<div class="fpd-cell-2"><span class="fpd-icon-add"></span></div>
</div>
<div class="fpd-list-row" id="1609962838288">
<div class="fpd-cell-0"><span class="fpd-current-color" style="background: white" data-colors=""></span></div>
<div class="fpd-cell-1"><textarea>Wanderlust</textarea></div>
<div class="fpd-cell-2"><span class="fpd-lock-element"><span class="fpd-icon-unlocked"></span></span>
</div>
</div>

How to use for loop through childNodes?

I need to set z-index dynamically on every node inside div (first node - 1, second - 2, etc). When I'm trying to use the "for" loop on childNodes, I got an error "Uncaught TypeError: Cannot set property 'zIndex' of undefined". Can you please point out my mistake?
You can see the codepen: https://codepen.io/pen/
HTML + JS:
<div id="blog__images" class="blog__images">
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
</div>
var images = document.getElementById('blog__images').childNodes;
for (var i = 1; i < images.length; ++i) {
images[i].style.zIndex = i;
}
Whitespace inside elements is considered as text, and text is considered as nodes. Those text nodes should be skipped.
var images = document.getElementById('blog__images').childNodes;
// console.log(images);
for (var i = 1; i < images.length; ++i) {
if (images[i] && images[i].nodeType != 3) {
console.log("My node:" + images[i].nodeName);
images[i].style.zIndex = i;
} else {
console.log("Skipping Extra node:" + images[i].nodeName);
}
}
<div id="blog__images" class="blog__images">
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
</div>
Set the z-index using .style and the iteration of i on each of your elements in your loop. Example below in snippit...
images[i].style.zIndex = i; will do the trick. I have selected the elements directly using the classname, no need for childNode...
You can open your browsers console and check the CSS properties for each node after you run the code.
Console for the snippit below once run:
let images = document.getElementsByClassName('image');
let imgZIndex;
for(let i = 0; i < images.length; i++){
imgZIndex = images[i].style.zIndex = i;
console.log(imgZIndex)
}
<div id="blog__images" class="blog__images">
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
</div>
You can loop over the structure like this.
var images = document.getElementById('blog__images').childNodes;
for (var img : images) {
images[img].style.zIndex = img;
}

use innerHTML to select class only if it is in a parent div

i currently have the code below which searches for the class and will replace the text.
how would i tweak it so it only will replace text if the parent tag is "#thumb-hockey-top"?
window.onload = function(){
//this captures all the elements with the spec classes
var soldItems = document.getElementsByClassName('product-mark sold-out');
//this changes each element 1 by 1 to new text
for(var i=0; i<soldItems.length; i++){
soldItems[i].innerHTML = "Coming Soon";
}
}
window.onload = function(){
//this captures all the elements with the spec classes
//just use a class
var soldItems = document.getElementsByClassName('sold-out');
//this changes each element 1 by 1 to new text
//var parentnode = document.getElementById('thumb-hockey-top')
for(var i=0; i<soldItems.length; i++){
if(soldItems[i].parentNode.id=='thumb-hockey-top'){
soldItems[i].innerHTML = "Coming Soon";
}
}
};
<div id="thumb-hockey-top">
<div class="product-mark sold-out"></div>
<div class="product-mark sold-out"></div>
<div class="product-mark sold-out"></div>
</div>
Use once
window.onload = function(){
//this captures all the elements with the spec classes
var soldItems = document.getElementById("thumb-hockey-top").getElementsByClassName('product-mark sold-out');
//this changes each element 1 by 1 to new text
for(var i=0; i<soldItems.length; i++){
soldItems[i].innerHTML = "Coming Soon"
}
}
<div id="thumb-hockey-top">
<div class="product-mark sold-out"></div>
</div>
<div class="product-mark sold-out"></div>
<div class="product-mark sold-out"></div>
Use multiple times
function myF(a, b){
// a = Id of parent element
// b = Class Name of element which you want to hack
var soldItems = document.getElementById(a).getElementsByClassName(b);
for(var i=0; i<soldItems.length; i++){
soldItems[i].innerHTML = "Coming Soon"
}
}
myF("thumb-hockey-top", "product-mark sold-out");
myF("thumb-hockey-bottom", "product-unmark sold-out");
<div class="example1">
<div id="thumb-hockey-top">
<div class="product-mark sold-out">EXAMPLE 1</div>
</div>
<div class="product-mark sold-out">EXAMPLE 1</div>
</div>
<div class="example2">
<div id="thumb-hockey-bottom">
<div class="product-unmark sold-out">EXAMPLE 2</div>
</div>
<div class="product-unmark sold-out">EXAMPLE 2</div>
</div>
You can get the parent element of an element using the parentElement attribute. Then just check its id.
var soldItem = soldItems[i];
if (soldItem.parentElement.id == "thumb-hockey-top") {
// do your thing
}

How to call a jquery event trigger while using a loop?

I have a problem in dealing with my problem. My problem is I am creating a static navigation. That uses trigger event. Because I am displaying a simple collapsible div.
What I did is I include all my id name in an array and I loop it to create an event. But when I click a link i doesn't call my jquery event. Is there a way how can I prevent hard coded of navigation?
Here's my sample code:
var toggleState = true;
var header_name = ["ParentA", "ParentB", "ParentC", "ParentD"];
var child_name = ["ChildA", "ChildB", "ChildC", "ChildD"];
for (var x = 0; x < header_name.length; x++) {
$("#" + header_name[x]).click(function (e) {
if (toggleState) {
$("#" + child_name[x]).show("slide");
} else {
$("#" + child_name[x]).hide("slide");
}
toggleState = !toggleState;
});
}
<div id="ParentA">Click A</div>
<div id="ChildA" style="display: none">Child A</div>
<div id="ParentB">Click A</div>
<div id="ChildB" style="display: none">Child B</div>
<div id="ParentC">Click A</div>
<div id="ChildC" style="display: none">Child C</div>
Here's the fiddle: http://jsfiddle.net/rochellecanale/cveze/3/
change this:
var header_name = ("Parent A", "Parent B", "Parent C", "Parent D");
to this
var header_name = ["Parent A", "Parent B", "Parent C", "Parent D"];
likewise with the next variable
You need to create a local copy of x for each iteration of the loop. The simplest way to do this is to create a helper function like getClickHandler:
function getClickHandler(x) {
return function(e){
if(toggleState){
$("#" + child_name[x]).show("slide");
}else{
$("#" + child_name[x]).hide("slide");
}
toggleState = !toggleState;
};
}
for(var x = 0; x < header_name.length; x++){
$("#" + header_name[x]).click(getClickHandler(x));
}
The key point here is that the function inside click runs at a later time (asynchronously). Because of how variable scope works in Javascript, your code passes the same reference to x in to each handler, which is why all of them end up getting the last iteration of the array. Doing the above creates a copy of x at the current iteration, and stores it in a local reference (inside the handler function).
If you can make minor changes to the html it should be as simple as
<div id="ParentA" class="click-toggle" data-target="#ChildA">Click A</div>
<div id="ChildA" style="display: none">Child A</div>
<div id="ParentB" class="click-toggle" data-target="#ChildB">Click B</div>
<div id="ChildB" style="display: none">Child B</div>
<div id="ParentC" class="click-toggle" data-target="#ChildC">Click C</div>
<div id="ChildC" style="display: none">Child C</div>
then
$(document).ready(function(){
$('.click-toggle').click(function () {
$($(this).data('target')).stop(true, true).slideToggle();
})
});
Demo: Fiddle
or even
<div id="ParentA" class="click-toggle">Click A</div>
<div id="ChildA" style="display: none">Child A</div>
<div id="ParentB" class="click-toggle">Click B</div>
<div id="ChildB" style="display: none">Child B</div>
<div id="ParentC" class="click-toggle">Click C</div>
<div id="ChildC" style="display: none">Child C</div>
then
$(document).ready(function(){
$('.click-toggle').click(function () {
$(this).next().stop(true, true).slideToggle();
})
});
Demo: Fiddle, if you want to maintain left -> right slide: Fiddle
to make your code work... the main problem is the use of shared closure variable toggleState... each menu item should have its own state variable... the solution is to create a private closure for each one
$(document).ready(function () {
var header_name = ["ParentA", "ParentB", "ParentC", "ParentD"];
var child_name = ["ChildA", "ChildB", "ChildC", "ChildD"];
$.each(header_name, function (idx, id) {
var toggleState = true;
$('#' + id).click(function () {
if (toggleState) {
$("#" + child_name[idx]).show("slide");
} else {
$("#" + child_name[idx]).hide("slide");
}
toggleState = !toggleState;
})
})
});
Demo: Fiddle

Hide DIVs with the same name using Javascript

I want to hide all divs with the name "mask"
This is my HTML:
<div id="first">
<div id="firsttest"></div>
<div class="one onehelp">
<div id="mask">
<div id="onetip"></div>
</div>
<div id="Div5"></div>
<div id="resultone"></div>
</div>
<div class="two twohelp">
<div id="mask">
<div id="twotip"></div>
</div>
<div id="Div6"></div>
<div id="resulttwo"></div>
</div>
<div class="three threehelp">
<div id="mask">
<div id="threetip"></div>
</div>
<div id="Div7"></div>
<div id="resultthree"></div>
</div>
</div>
I tried to hide "mask" by using the JS code below but it didn't work for all divs, just for the first one.
var hidemask = document.getElementById("mask");
hidemask.style.display = "none";
Is there a way to hide them all by using pure Javascript. No jQuery.
You shouldn't be using duplicate ID's in HTML, consider changing it to a class.
If you change id="mask" to class="mask", then you can do:
var hidemask = document.querySelectorAll(".mask");
for (var i = 0; i < hidemask.length; i++) {
hidemask[i].style.display = "none";
}
Or for browsers still in the stone age (IE7 and below), you can do:
var elems = document.getElementsByTagName('*'), i;
for (i in elems) {
if((' ' + elems[i].className + ' ').indexOf(' ' + 'mask' + ' ') > -1) {
elems[i].style.display = "none";
}
}
The id attribute must be unique per document. You can do what you want with a class, perhaps. So you would have multiple divs like so:
<div id="something" class="mask"></div>
Then you can do:
var divsWithMask = document.querySelectorAll(".mask");
for(var i = 0; i < divsWithMark.length; i++) {
divsWithMak[i].style.display = "none";
}
You cannot assign same ID more than once.
But you can add an attribute class to div with id "mask" E.g.:
<div id="mask-or-something-else" class="mask">...</div>
And select all elements by this class:
var hidemask = document.getElementsByClassName("mask");
for(i = 0; i < hidemask.length; i++)
hidemask[i].style.display = "none";

Categories

Resources