jQuery: Find first two children - javascript

Using jQuery, what would be the most efficient way to find the first two children of a parent element, if one is an h1 and the other is a p. My code isn't working right now, and I would like to accomplish this using best practices.
CSS
div > *{
display: none;
}
HTML
<div>
<h1>Heading</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</div>
<div>
<h1>Heading</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</div>
Javascript
$('div h1').show();
$('div p:first-child').show();
Edit I'm actually working with multiple DIVs. I didn't think it would make a difference, but it looks like I was wrong.

Try,
$('div').children().slice(0,2).show();
Incase if you have more that 1 div, then try like below,
$('div').each (function () {
$(this).children().slice(0,2).show();
});

an alternative way to slice() method:
$('div').children(':lt(2)').show()
(but I recommend the slice too, especially for large collections)

http://jsfiddle.net/94EU7/
$('div :lt(2)').show();

You can user the less than selector like following
$('div > *:lt(2)').show();
Working fiddle

A descriptive selector would be
$('div').find('h1:first, p:first').show();
This makes it clear what your intent is and what elements you're selecting.

$('div p:first-child,div p:nth-child(2)').show();

$('div').children().slice(0, 2).show();

I think you'll want the eq() function, like this:
$("div").children().eq(0); // first child
$("div").children().eq(1); // second child

Not sure why you need to use jQuery for this.
var firstChild = div.firstChild;
firstChild.style.display = 'initial';
firstChild.nextSibling.style.display = 'initial';

Related

Find element that is not inside specific parent

I am trying to figure out how to find an element that is NOT inside specific parent. Here is a sample html:
<div class="id01">
<p>some text</p>
</div>
<p>some more text</p>
<p>some more more text</p>
Ok, now I need to find a first paragraph that is not inside parent #id01 and that is where I am getting lost. I started to do it like that
$('p:first').text(); //this way i would get the P inside DIV but I want to skip that one and count on next one that has no parent #01
Hope i made it clear.
You could easily use the :not() selector for that, in combination with :first .
$("p:not(.id01 p):first").text()
JSFiddle.
Solution 1 :
$('p').not('.id01 *').eq(0)
Solution 2 :
$('p').filter(function(){ return $(this).closest('.id01').length==0 }).eq(0)
Very simple way, as suggest by adamb all this stuff is on the jQuery site, but here
$("p:first").not($(".id01 p"));
Should give you what you want.
you could use the .next() selector
$("div.id01").next('p')
Use eq() for the index of <p>
console.log($('p').eq(1).text()); //some more text
console.log($('p').eq(2).text()); //some more more text

Jquery - Accessing nested child elements

Assume I have the following HTML -
<DIV id="ParentDiv">
<DIV id="SubDiv1"></DIV>
<DIV id="SubDiv2">
<INPUT id="input">
</DIV>
</DIV>
To access the input element using jquery, it would be simply $("#input"). What I'm trying to do is access it, assuming I only know the ID of the top level div.
Currently I have
$($($("#ParentDiv").children()[1]).children()[0])
Which does seem to work. Is there a cleaner way of writing this, or is the way I am doing it ok?
You would just perform a .find() implicitly or explicitly:
$('#ParentDiv input'); // implicitly
$('#ParentDiv').find('input'); // explicitly
Reference: .find()
You can try:
1. $('#ParentDiv input')
2. $('input', '#ParentDiv')
3. $('#ParentDiv').find('input')
if you need to find the input from SubDiv2 only upon having parentDiv information you can use
$("#ParentDiv div:eq(1) input")
or
$("#ParentDiv div:eq(1)").find("input")
Where eq(1) will get you with the second div inside ParentDiv
Try this:
$('#ParentDiv').find('input');
Many ways to do it. Here is one
$("#ParentDiv > div:eq(1) > input")
how about
$("#ParentDiv :input")
try this
jQuery('#input').val();

Change position of tags in the DOM

<p>I like turtles</p>
<h3>Child brags about stuff</h3>
<h4>The Herd</h4>
How do I change the positions (order) of a tag?
To this:
<h3>Child brags about stuff</h3>
<p>I like turtles</p>
<h4>The Herd</h4>
Is there a JQuery possibility?
Use .detach() and .insertAfter() jQuery methods, like so:
$(function() {
$('p').detach().insertAfter('h3');
});
jsFiddle proof.
With jQuery:
$('h3').after($('p'));
Also see my jsfiddle.
If you have the h3 in the variable h3elem and the p in pelem (get them there however you want - jQuery, getElementById or getElementsByTagName, or anything really), use:
h3elem.parentNode.insertBefore(h3elem, pelem);
This moves the h3 to before the p.
The below code will insert <h3> tag before <p> tag, you can assign them an id to identify them uniquely.
$('h3').insertBefore($('p'));
function doWorks(){
var h3 = $("h3");
h3.remove();
h3.insertBefore("p");
}

How can I say this in jQuery?

I want to append some text after 2 closing divs to a sector element.
Click me
</div>
</div>
// this is where I want to append the text
My code appends the text after the link. How can I say "append it after the 2nd closing div"?
$('a.thingIClicked').click(function() {
$(this).append('hello');
});
The most direct way to do this is to find the second parent <div> element, and then insert the text after it.
$('a.thingIClicked').click(function() {
$(this).parent("div").parent("div").after("some text");
});
This will insert the text on the outside of the second <div> parent. Using append() will put the text on the inside of the parent, which from your example doesn't appear to be what you want.
There's probably a more elegant solution, but how about:
$('a.thingIClicked').click(function() {
$(this).parent().parent().after('hello');
});
Edit: #Zack is correct (and should probably get the answer credit for this one) - my original code would have added the text into the second enclosing div, rather than after it. I've edited my code above accordingly.
The easiest way would be to give the outer div an id and then use $("#outerdivid").
EDIT: Below will not work, but leaving it here for reference
However, you should also be able to use a jquery :parent filter:
http://api.jquery.com/filter/
$('a.thingIClicked').filter(':parent').filter(':parent').click(/**/);
Use .insertAfter()
http://api.jquery.com/insertAfter/
<div class="container">
<h2>Greetings</h2>
<div>Hello</div>
<div class="inner">Goodbye</div>
</div>
We can create content and insert it after several elements at once:
$('<p>Test</p>').insertAfter('.inner');
Use .insertAfter() - http://api.jquery.com/insertAfter/
<div class="container">
<h2>Greetings</h2>
<div>Hello</div>
<div class="inner">Goodbye</div>
</div>
We can create content and insert it after several elements at once:
$('<p>Test</p>').insertAfter('.inner');

jquery select multiple <p> in <div>

HTML:
<div id='example'>
<p> First paragraph</p>
<p> Second paragraph</p>
<p> Third paragraph</p>
</div>
Javascript with JQuery:
var paragraphs = $('div#examples p');
This returns an array of HTMLParagraphElement objects. However, I wish to return Jquery objects. (So that I can use e.g:
for(i=0;i<paragraphs.length;i++)
{
paragraph[i].hide();
}
Is there a way I can easily do this? Thanks.
example:
$('#examples p').hide();
div is not necessary
This the the most performant way to query the dom for present issue:
$('#examples).find('p').hide();
It's a few more keystrokes, but the selection happens so much faster than the examples given here by others. The reason being is that it traverses all divs first, then finds those that may have the given id, then traverses to find their matching p tags.
In my solution it finds just #examples and then traverses down to its p tag.
You can still use the the selector query you use. i.e:
var paragraphs = $('div#examples p');
paragraphs.hide();
or
$('div#examples p').hide();
Thanks everybody for input. Iteration of the div p array was necessary (sorry if that wasn't clear), so doing $('div#example p').hide(); was not a proper solution. I ended up doing the following:
var arr = $('div#example p');
for(i=0;i<arr.length;i++)
{
$(arr[i]).hide();
}
Hope this is useful for people in the future:)
try this...
$('div#examples p').hide();
From the looks of your question the answer would be, as stated by others:
$('div#examples p').hide();
But for the case that you have to iterate through each object that is returned from a jQuery query you should use this syntax:
$('div#examples p').each(function(){
$(this).hide();
});
But remember, if it's as simple as hide, then just use the first example. The second example is when the applied function is specific to each object. The next example is doubling the heights of all returned objects, which could not be done in the same way that the first example is:
$('div#examples p').each(function(){
var h = $(this).height();
$(this).height(h * 2);
});

Categories