Append to an object selected from a list in jQuery - javascript

Here is a minimal version of my problem, given:
<div class="foo">
<div class="a"> </div>
<div class="b"> </div>
<div class="c"> </div>
</div>
I want to insert the element <div class="bar">WORKS!</div> into one of the children randomly.
var kids = $(.foo).children();
var idx = Math.floor(Math.random() * kids.length);
var target = kids[idx];
I think this is a misunderstanding between how javascript and jQuery work together. I'm learning both at the moment, so here is my due diligence in solving the problem:
target.append(...) fails since target is not a JQuery object and .append() is a JQuery call.
$(target).append(...) does strange things, copying items around in the DOM and I don't understand why. It may work in this isolated example, but it's causing crazy town with many foo's, a's, b's and c's.
target.innerHTML=... doesn't seem to work and I don't want to erase any previous content with the append.

Try,
var target = kids.eq(idx);
instead of,
var target = kids[idx];
Please read here to know more about .eq()

Try .eq()
var target = kids.eq(idx);

Related

JavaScript equivalent to JQuery .next()

Is there a JavaScript method similar to jQuery .next()? I want to find the next element that has the class of "error" relative to the element. I've tried using .nextSibling as a loop but couldn't figure it out. Didn't know if there was an easier way to go about it without jQuery.
For instance, if I have this code:
<div id="section">
<div id="test">test</div>
<span class="info">Information</span>
<span class="error">Error!</span>
</div>
I'm trying to get the next .error class closest to #test, if I have a #section2 and a #test2 I would want to get the .error class closest to #test2 and so on.
The nextElementSibling property returns the element immediately following the specified element, in the same tree level.
Example: Get the HTML content of the next sibling of a list item:
var x = document.getElementById("item1").nextElementSibling
The nextElementSibling property might help.
Best bet would be to search through the jQuery code and see what they did.
http://code.jquery.com/jquery-2.0.3.js
At a glance, I do see some calls to "nextSibling" and "previousSibling."
Also see here:
How to get next element using JavaScript-only?
Hope this helps!
This is the pure javascript for you:
HTML
<div id="nodes">
<div class="error">This is error Node</div>
<div class="nextElement">This is next Element</div>
</div>
Javscript:
var nodes = Array.prototype.slice.call( document.getElementById('nodes').children ),
errorNode = document.getElementsByClassName('error')[0];
var indexOfError = nodes.indexOf(errorNode);
var nextElement = nodes[indexOfError + 1];
alert(nextElement.innerText);
Here is demo
Sounds like you may be looking for document.getElementsByClassName()... if the elements with class=error are not direct siblings in the DOM, then there's not a good way to find them otherwise. It's elementary, but you can just search through the array returned by document.getElementsByClassName('error') until you find your starting element, and then you know the next item in the array will be the next element in the DOM.
See also MDN reference. Won't work in old IE, but works for all modern browsers.

Appending a div on unknodw div

I have three divs. How should I append a div onto an unknown div?
<div class="main" >
<div id="drag-box" >
<div id="" class=""> </div>
</div>
</div>
I want to append div on an unknown div which is come after drag-box div. I don't know which div comes after drag-box div. But there must be one div after drag-box div.
$("#drag-box div:first-child").append("<span />");
or
$("#drag-box div").first().prepend("<span>first</span>");
For a complete answers, here it is working:
http://jsfiddle.net/dMUD3/
try this
$("#drag-box div:first-child").attr("id");
Instead of giving you a one liner I would like to give you an indepth solution.
A browser takes your html and parses what is called a DOM Tree out of it.
so if your html is .
<div class="a">
<div class="foo"></div>
<button class="foogle"></button>
</div>
The tree structure will become something like
`-div.a
|-div.foo
`Button.foogle
You should actually look into DOM Api's at MDN
How DOM helps ?
With DOM api's you can actually access the unknown div using the reference to a known div. So if you actually understand your markup and its representation in DOM it should be pretty simple to get reference to nth child of an element;
You can access the child elements by the children attribute.
So
// Get reference to the element.
var parent = document.getElementById("drag-box");
// Use the dom.
var child_i_want = parent.children[0];
// or there is another way
var child_i_reallyWant = parent.firstElementChild;
There are solutions with jQuery but I feel its important for you to Understand basics of DOM even when there are helpful abstraction libraries in existance.
You'll need the + selector. It applies to the object directly following. See here.
.drag-box + div {
}
$('<div></div>').appendTo($('#drag-box div:first'))

Counting div's with class and returning position

I have a page with many dynamically creted div's as seen below:
<div class="open"></div>
<div class="open"></div>
<div class="open"></div>
<div class="open"></div>
I'm looking for a way to get get a position of an element (eg. If the element is the first instance of, assign id="1" if element is the second instance of, assign id="2".
I'm currently using the following jquery, but am stuck, as Im not sure where to go from here.
$(document).ready(function () {
var numDialogs = $('.open').length;
});
Any suggestions?
Just use:
$('div.open').prop('id', function(i){
return 'openElement' + (i + 1);
});
JS Fiddle demo.
I've deliberately added a prefix string because while numerical ids are valid under HTML5, they remain invalid under HTML4, and are difficult to select using CSS selectors.
References:
prop().
Mark, you can target the element and then add an attribute like so:
$('.open').attr('id', numDialogs);
This will give it all 4's in this case, but I'll leave you to wrestle with the actual logic to implement the right numbers. Good luck.

is using find() in this simple case overkill?

If you are caching elements with javascript, which is more efficient?
HTML
<div id="parent">
<div id="child"></div>
</div>
Javascript:
var parent = $('#parent');
var child = $('#child');
or
var parent = $('#parent');
var child = $(parent).find('#child');
Is one better than the other? Or better practise? I'm writing a lot of code like this, and I am currently using find() to get specific elements of parents that are already cached.
Thanks
As #PSL says, as ids, the first is better, but with classes, the second would be faster because then you don't have to search the whole document for .child you just have to search within the #parent
Also, you can go:
var child = parent.find('#child');
instead of
var child = $(parent).find('#child');

Find the number of div elements under a parent div

Is there a jquery method that allows you to find the number of div elements under a parent node.
So say I have this set up
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
</div>
If I want to find the number of divs under parent it would be 2
or this
<div id="parent">
<div id="child1"><div id="childer1"></div></div>
<div id="child2"></div>
</div>
It should give me 3.
Is there any method that does that for you?
Yes. If you want all of them:
var divs = $('#parent').find('div').length;
or
var divs = $('#parent div').length;
If you just want the immediate children:
var divs = $('#parent').children('div').length;
or
var divs = $('#parent > div').length;
The variations involving "find" and "children" are handy in case your starting element is something for which you've already got a reference.
This should do it:
var descendant_count = $("#parent div").length;
Pure vanilla solution:
document.getElementById('parent').querySelectorAll('div').length;
jsFiddle here.
To note: querySelectorAll() is only supported in more recent versions of IE (as of IE8+).
Without a library
document.getElementById("parent_div").children.length;
You can get number using length
$('#parent div').length
Try:
$('#parent').find('div').length;

Categories