I have a page where a plugin adds child div's to a parent div at random time interval.
The basic structure is :
<div id="parent">
<div class="child" someattr="abc">content1</div>
<div class="child" someattr="xyz">content2</div>
</div>
I tried the following to detect adding of elements and it works
var c = document.getElementById('parent');
c.__appendChild = c.appendChild;
c.appendChild = function(){
alert("Added");
c.__appendChild.apply(c, arguments);
}
I got the above from an answer in stackoverflow itself.
What I would also like to do is to get the contents of the child divs.
That is, their attributes and the content inside.
What would be the easiest/best way to go on this.
I wouldn't mind if the solution is jquery
No jQuery needed:
document.getElementById('parent').innerHTML;
Of course you could use jQuery as well, because it might help you get the individual children:
$('#parent .child').each(
function(){
// In this context, 'this' points to the current child element in the itertion
}
Related
Forgive my ignorance, I'll try to be as clear as possible. I'm trying to modify an existing JS function that adds a class to a parent element. I would like to modify it to add the same class to a sibling of the parent, in this case the aside '.footnote-right-col'.
I have tried a good number of ways but this is beyond me. I'm not sure if I need to create a new function and call it separately, or if I can simply add a new variable to this function. I presume the way I would target the parent is via getParent.nextSibling
As is JS
open: function (el) {
this.footnote.el = getParent(el, '.footnote-container')
var popover = this.footnote.popover()
this.footnote.el.classList.add('is-open')
this.sizeFootnote()
popover.classList.remove('is-hidden')
this.positionFootnote()
popover.classList.add('is-visible')
window.addEventListener("resize", self.resize.bind(self))
},
Rendered HTML
<div class="footnote-container open-down">
<button class="footnote-button" title="view footnote #1">...</button>
<aside class="footnote-popover is-hidden">...</aside>
</div>
<aside class="footnote-right-col is-hidden">...</aside>
this.footnote.el.nextElementSibling Should get you .footnote-right-col element if I am understanding how you set things. If this.footnote.el is the <div class="footnote-container open-down"> element then my answer works. Once you have that div you can just call the .nextElementSibling
EDIT:
ok so cool if this.footnote.el is the button then simply do this:
this.footnote.el.parentElement.nextElementSibling and you should have it!
So to add the class:
this.footnote.el.parentElement.nextElementSibling.classList.add('is-open')
I have two pages in my site.
Page one code is dynamic. and there is a section which generates dynamically.
These are the classes which generates for that section :
div.when, div.where, div.planner, div.capacity, div.websites
I want to use that same section in my page two inside below div.
<div class="add-to-calendar"> </div>
I am not getting any clue how can I do it with jquery or javascript.
I need help in this.
You can use append method to include any element inside div.
Html:
<div class="innerdiv"> Inner Div</div>
<div class="add-to-calendar">Outer Div </div>
Jquery :
.append method will insert inner div to your outer div.
$(".add-to-calendar").append($(".innerdiv"));
If your page refreshed, No problem you can maintain element in localstorage.
use below code to maintain the element and use it.
var testObject = $(".innerdiv").html(); // get the element
localStorage.setItem('element', testObject ); // Put the object into localstorage
var getTestObject = localStorage.getItem('element'); // use the element
$(".add-to-calendar").append($(getTestObject)); // Insert element
I'm thinking if I override a div's html with the jQuery html() method all 'old' DOM elements and all listeners removed from the memory?
For example:
HTML:
<div id='aDiv'>
<div id='anANotherDiv'>An Another Div</div>
</div>
Javascript:
$('anANotherDiv').click(function(){
var b='An Another Div'
console.log(b);
});
$('#aDiv').html('<div id='oDiv'>This div override the another</div>');
$('#oDiv').click(function(){
var a='This div override the another';
console.log(a);
});
So when I overrid the old the GC will be delete the old DOM elements and listeners?
Okay !! Lets start from this way .
Here is your HTML
<div id='aDiv'>
<div id='anANotherDiv'>An Another Div</div>
</div>
Now aDiv is containing only one div as it's child and it is anANotherDiv . Now when you go for this on your console
$("#adIV").html();
The console output will be
<div id='anANotherDiv'>An Another Div</div>
Now when you go for something like this on your console
$('#aDiv').html('<div id=\"oDiv\">This div override the another</div>');
The console output will be only
<div id="oDiv">This div override the another</div>
You are actually manipulating completely the entire aDiv strucuture . .html() basically changes the HTML structure . So you need to make sure whether you want to completely change the HTML structure of a particular element or node or you just have to append or do some other stuffs
Hope I am clear to you .
Cheers !!
You can use on method from jQuery, you can use it to bind the event with reference to parent element so even if you change the actual target DIV's content, event will get attached as we have bind event with reference to parent element.
//Example:
<div id='aDiv'>
<div id='anANotherDiv'>An Another Div</div>
</div>
$(function(){
$("#aDiv").on("click", "div", function(){
var a='This div override the another';
console.log(a);
});
});
To solve event listeners problem, I usually use "global click" approach (JSFiddle):
HTML
<div id="div1" data-clickable>
Parent Click
<div id="div2" data-clickable>
Child ClickClicks
</div>
</div>
JS
$(document.body).click(function(e){
var n="[data-clickable]", $t = $(e.target).is(n) ? $(e.target) : $(e.target).parents(n+":first");
switch ($t.attr('id')){
case 'div1':
console.debug("DIV1 clicked");
break;
case 'div2':
console.debug("DIV2 clicked");
break;
}
});
It listens to body's clicks, and then decides if that was the click we are waiting for.
As for elements replacement problem, there is nothing you can do. You have to come up with some other approach rather than .html()
The scenario looks like below, right now it changes the color of "Test" text:
<div class="item">
<div class="number">4</div>
<a onclick="ChangeColor(this)">Test</a>
</div>
<script>
function ChangeColor(e) {
e.style.color = '#85BD49';
}
</script>
Demo
What I am trying to do is to change the background color and the text color of the div number class.
How can I do that by using the event object? I am not looking for a solution with jQuery or other ways.
Any kind of tips or help is appreciated I have tried parentNode and offsetNode but its not working.
parentNode is the right thing to use, but you then need to get the right child.
e.parentNode.children[0].style.backgroundColor = 'red'; will work, assuming .number is the first child of the parent of the link.
You could also do:
e.parentNode.querySelector(".number").style.backgroundColor = 'red';
I'm quite new to javascript and JQuery programming. Usually, to access elements I give them an id, so I can get them like $("#"+id).blabla().
But now I need to dynamically create a div, and access elements inside it.
Something like
<div id="automaticallyGeneratedId">
<div ???></div> <!-- first div -->
<div ???></div> <!-- second div -->
</div>
What are the best practices to access and identify each of the inner divs?
I generate another id for them?
Or what?
I don't have the theory of selectors fully clear.
edit: modified the question from identifying a single inner div to identifying divs amongs many of them
You can maintain a pattern when you're generating id. For example:
if you always generate id like: myid1, myid2,myid3...
<div id="myid1">
<div></div>
</div>
<div id="myid2">
<div></div>
</div>
......
then you can try:
$('div[id^=myid]').find('div').foo();
OR
$('div[id^=myid] div').foo();
Here, ^= is start with selector, so div[id^=myid] will select div whose id start with myid.
You can also use Contain word selector which is ~= and use like $('div[id~=myid]'). This will select div with id contains word myid.
Instead of id if you want to use other attribute eg. name then change selector like:
$('div[name^=myid]') or $('div[name~=myid]').
It's usually a good practice that if you already have a reference to that outer div to just search from there using find.
You can give it an id, or if you want to use a more general approach you can use classes.
<div class="subdiv">...
$('#automaticallyGeneratedId').find('div.subdiv')
Usually, when you create them, you can assign event handlers and the likes straight on them. Like this:
var div = $( '<div></div>' );
div.on( 'click', function() {
// Do something when the generated div is clicked
});
// Then, add it to the DOM
$( 'body' ).append( div );
You don't need to bother selecting them with ID or classes, they're already available in your code.
Another way is to use event bubbling to handle newly created elements of the same class. A good link about this is this one: http://beneverard.co.uk/blog/understanding-event-delegation/
Many ways you can create an element and give him an Id or Class, or use the DOM to access it..
$("html").prepend('<div id="foo"></div>');
$("#foo").doSomething();
another way
$("#automaticallyGeneratedId").find("div").doSomething();
To access the div in the element with the id:
$("#automaticallyGeneratedId div").whatever
If you cache the divs you could use something like:
var myDiv1Child = $('div', myDiv1);
Create a delegated listener and within the listener you can find the element by doing this
//If a div inside the parent is clicked then execute the function within
$('.PARENT_CLASS').click("div", function(){
//This variable holds all the elements within the div
var rows = document.querySelector('.PARENT_CLASS').getElementsByTagName('div');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
console.log(this); //The element you wish to manipulate
}
}
});