D3 adding multiple children to the same parent - javascript

How would I go about adding multiple child elements to a parent?
This is what I would like to achieve :
<div id = "myDiv">
<div id = "child1"></div>
<div id = "child2"></div>
</div>
This would, however, make child2 a child of child1:
$("#myDiv").append("div").attr("id", "child1").append("div").attr("id","child2")
Is there any way of adding two children with different attributes using dot notation?
EDIT: How about also appending a child to child1?

$("#myDiv").append("<div id='child1'>").append("<div id='child2'>")

And another
$('#myDiv').append($('<div>', { id: 'child1' })).append($('<div>', { id: 'child2' }))

$("#myDiv").append("div").attr("id", "child1").append("div").attr("id","child2");
Appends "div" text to myDiv, then changes the id attribute of the div formerly known as "myDiv" to "child1" then appends more text and changes the id again.
Change form of your statements:
$("<div>").attr("id", "child3").add($("<div>").attr("id", "child4")).appendTo("#myDiv");
With this, jQuery creates a properly formed div, assigns and id attribute to it, then adds another div with and id. Note that the second addition with .add() is properly formed due to the $ inside there and the id attribute added before it gets added to the first one, then they both get appended.
NOTE: you can also use the pattern above or do simple string for the child of child1 as:
$("<div id='child1A'/><div id='child1B'/>").appendTo("#child1");
Worth noting this only hits the DOM once which is desired and you can build up the string to append more as well - still only hitting the DOM once with that append.

You could clone() #myDiv to a variable, loop up to the number of child elements needed, change the attribute and then appendTo #myDiv. I know right, kinda complex.
Perhaps you're better off using append two times. (In two separate lines, no chaining)
Oh wait, you could use add (Here's a fiddle : http://jsfiddle.net/w4qnk/)
$elemts = $()
$elemts = $elemts.add($('<div/>', { 'id': 'child1'}))
$elemts = $elemts.add($('<div/>', { 'id': 'child2'}))
$("#myDiv").append($elemts)

Related

Meaning and usage of jquery find('>')

I'm working on a javascript code which does :
$('div').html(<some text>).find('>')
Looking at the jQuery documentation, I can't understand what find('>') is supposed to do.
Moreover, when experimenting in navigator console, I get strange results :
$('div').html('to<br/>to').find('>') -> [ <br>​, <br>​, <br>​]
$('div').html('to<a/>to').find('>') -> [ <a>​</a>​, <a>​</a>​, <a>​</a>​]
Why a 3 times repetiton ?
So, can anyone enlighten me about this strange find('>') ?
> is the Child Combinator CSS selector. .find('>') will pull all direct children of the element.
As mentioned in comments, the repetitions must be due to your document having multiple div elements.
Update
From your comment:
I thought the line was creating a div then setting some html into it.
$('div') itself selects all div elements which exist within document. If you want to create a div element, you can instead do this:
$('<div/>', { html: 'to<br/>to' });
If you're new to jQuery, I'd strongly advise checking out http://try.jquery.com and http://learn.jquery.com.
As someone pointed out, '>' selects the child elements of an element.
Why 3? Because surely you have 3 divs, so
$('div') //selects 3 divs
.html(...) // adds content to each div
.find('>'); //return the direct descendants of each element in the jQuery object
//as a new jQuery object

jQuery: Using .after() or .before() adds element to last item in selection only

I've been using jQuery for a while but this is a new one. A simplified example:
HTML
<div class='custom'></div>
<div class='custom'></div>
<div class='custom'></div>
jQuery:
var $customElems = $('.custom'),
$spanOuter = $('<span class="outer"/>'),
$spanInner = $('<span class="inner"/>');
$customElems.each( function() {
$(this).wrap($spanOuter).after($spanInner);
});
JSFiddle:
http://jsfiddle.net/a3ZK8/
I would have expected the 'inner' span to be added to all three elements in the selection but it gets always inserted into the last one only (no matter how many). I tried it with .before(), with and without the chaining, same result. What am I missing??
The problem is you are using a reference to a jQuery object.
Hence you keep moving the object reference around within each iteration.
If you have no events attached or no need for the span to be a jQuery object then just pass the parameter as a HTML string literal instead of an object reference
Cloning a jQuery object that doesn't need to be a jQuery object in the first place is just redundant processing and unnecessary overhead.
Change your jQuery object to a string similar to this:
spanInnerString = '<span class="inner"/>';
and your method like this:
$(this).wrap($spanOuter).after(spanInner);
The result is:
<span class="outer"><div class="custom"></div><span class="inner"></span></span>
<span class="outer"><div class="custom"></div><span class="inner"></span></span>
<span class="outer"><div class="custom"></div><span class="inner"></span></span>
DEMO - Passing parameter as HTML string
Off course, the same goes for the outer span. Don't create jQuery objects unless you have to.
If you must use a jQuery object because you want to attach events to the span or similar, than cloning is the way to go, though make sure you use clone(true, true) then to also clone the attached events.
You need to clone the element. Otherwise, after() will relocate the same element 3 times, which results in it being attached to only the last looped element.
$customElems.each(function () {
$(this).wrap($spanOuter).after($spanInner.clone());
});
Demo: Fiddle
You might ask, "Why would wrap() work?" That's because 'wrap()' internally clones the element.
You're moving the same span from place to place. If you acted on all three divs at once, jquery will instead clone the span.
http://jsfiddle.net/a3ZK8/1/
var $customElems = $('.custom'),
$spanOuter = $('<span class="outer"/>'),
$spanInner = $('<span class="inner"/>');
$customElems.wrap($spanOuter).after($spanInner);
From the documentation for .after:
Important: If there is more than one target element, cloned
copies of the inserted element will be created for each target except
for the last one.
which means the last element will always get the original, while all other selected elements will get a clone. That's why when you acted on one element at a time, it simply moved the same span around.

Accessing elements inside dynamically created divs with HTML/Javascript

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
}
}
});

Removing a child div from a parent div in jquery

I am trying to delete the child element in the dom from its parent using jquery.
Here is the code snippet.
$('#delete').live('click' , function() {
var strchild = m.split("/",2)[1];
var c = group.children(strchild);
c.remove();
});
strchild contains the id of the child element. group is the parent object. I am getting the right child element in the variable c. But the remove function fails.
Can some help me out here.
Thanks.
If you have
strchild
as the id of the element you want to remove, you can do
$("#" + strchild).remove()
assuming it is the only element with that id (it should be, that's the whole point of id).
EDIT:
With multiple ids, you would need to reference the parent specifically. This is very simple, since you say in your question that group is the parent object. This answer assumes it is the object itself, rather than the id, as your code sample implies.
$("#" + strchild, group).remove()
Adding the second argument here constrains the selector to the specifications of that second argument. So this will search the parent (group) for an element with the id strchild, and then remove that element.

javascript get child by id

<div onclick="test(this)">
Test
<div id="child">child</div>
</div>
I want to change the style of the child div when the parent div is clicked. How do I reference it? I would like to be able to reference it by ID as the the html in the parent div could change and the child won't be the first child etc.
function test(el){
el.childNode["child"].style.display = "none";
}
Something like that, where I can reference the child node by id and set the style of it.
Thanks.
EDIT: Point taken with IDs needing to be unique. So let me revise my question a little. I would hate to have to create unique IDs for every element that gets added to the page. The parent div is added dynamically. (sort of like a page notes system). And then there is this child div. I would like to be able to do something like this: el.getElementsByName("options").item(0).style.display = "block";
If I replace el with document, it works fine, but it doesn't to every "options" child div on the page. Whereas, I want to be able to click the parent div, and have the child div do something (like go away for example).
If I have to dynamically create a million (exaggerated) div IDs, I will, but I would rather not. Any ideas?
In modern browsers (IE8, Firefox, Chrome, Opera, Safari) you can use querySelector():
function test(el){
el.querySelector("#child").style.display = "none";
}
For older browsers (<=IE7), you would have to use some sort of library, such as Sizzle or a framework, such as jQuery, to work with selectors.
As mentioned, IDs are supposed to be unique within a document, so it's easiest to just use document.getElementById("child").
This works well:
function test(el){
el.childNodes.item("child").style.display = "none";
}
If the argument of item() function is an integer, the function will treat it as an index. If the argument is a string, then the function searches for name or ID of element.
If the child is always going to be a specific tag then you could do it like this
function test(el)
{
var children = el.getElementsByTagName('div');// any tag could be used here..
for(var i = 0; i< children.length;i++)
{
if (children[i].getAttribute('id') == 'child') // any attribute could be used here
{
// do what ever you want with the element..
// children[i] holds the element at the moment..
}
}
}
document.getElementById('child') should return you the correct element - remember that id's need to be unique across a document to make it valid anyway.
edit : see this page - ids MUST be unique.
edit edit : alternate way to solve the problem :
<div onclick="test('child1')">
Test
<div id="child1">child</div>
</div>
then you just need the test() function to look up the element by id that you passed in.
If you want to find specific child DOM element use method querySelectorAll
var $form = document.getElementById("contactFrm");
in $form variable we can search which child element we want :)
For more details about how to use querySelectorAll check this page

Categories

Resources