jQuery first of type selector? - javascript

How would I select the first <p> element in the following <div> with jQuery?
<div>
<h1>heading</h1>
<p>How do I select this element with jQuery?</p>
<p>Another paragraph</p>
</div>

Assuming you have a reference to the div already:
$(yourDiv).find("p").eq(0);
If the first p will always be a direct child of the div, you could use children instead of find.
Some alternatives include:
$(yourDiv).find("p:eq(0)"); //Slower than the `.eq` method
$(yourDiv).find("p:first");
$(yourDiv).find("p").first() //Just an alias for `.eq(0)`
Note that the eq method will always be the fastest way to do this. Here's the results of a quick comparison of the eq method, :eq selector and :first selector (I didn't bother with the first method since it's just an alias of eq(0)):

$('div p:first')
answer was too short to post without this useless sentence.
Edit
This is definitely a slow option. After looking at Jame's speed test, it looks like jQuery selectors work best when they piggy back off of css selectors.

$("div p").first();
or $('div p:first');
Reference: http://api.jquery.com/first/
Keep in mind that first() matches only a single element, the :first-child selector can match more than one: one for each parent.

You almost know the answer (from your post title). There is a selector in jQuery called :first-of-type. Use it to find and add class to the first p tag automatically, like so:
$("div p:first-of-type").addClass('someClass');

$('div p').first()
Should work. I think.

This should work
$( "div p:first-of-type" ).css( "font-size: 10px" );
The above code finds the first paragraph in the div as #Denver pointed and changed its fonts-size to 10px
Here is an example that explains even more about jQuery first-of-type selector

Related

Move element before second to last h2 with jQuery

I am trying to move an elmement with class .books_inarticle_list from its native possition tu just before the second to last H2.
I am using the following which is not working:
$('.books_inarticle_list').insertBefore('#content_column > h2:nth-last-child(2)');
On the other hand something like this works:
$('.books_inarticle_list').insertBefore('#content_column > h2:nth-of-type(6)');
So the issue must be with the nth-last-child() selector, but I don't see what it might be.
Does anyone see anything wrong with that code or knows an alternative way to move that element to just before the second to last H2 tag?
Try the .get() method, which supports negative numbers to go in reverse.
$('.books_inarticle_list').insertBefore($('#content_column > h2').get(-2));
Edit On second thought, it makes more sense to follow your own examples and use the :nth-last-of-type() selector, which will go in reverse.
$('.books_inarticle_list').insertBefore('#content_column > h2:nth-last-of-type(2)');
The reason :nth-last-child() isn't working for you is because that, and :nth-child(), refers to the number of siblings they have in the DOM, not the list of elements returned by the selector.
You'd be better off providing your HTML for the optimal solution, however given your question I'd suggest something like the following:
var $h2s = $("#content_column > h2");
var $secondToLast = $h2s.eq($h2s.length-2);
$('.books_inarticle_list').insertBefore($secondToLast);
I passed on using nth-child just because that will be thrown off any time you modify your HTML structure.
Note, :nth-* selectors use 1-based indexing. You can use :nth-last-of-type() selector with 2 as parameter to selector second from last element of that type, chain .before() with $(".books_article_list") as parameter.
$("#content_column h2:nth-last-of-type(2)").before($(".books_article_list"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="books_article_list">books</div>
<div id="content_column">
<h2>0</h2>
<h2>1</h2>
<h2>2</h2>
<h2>3</h2>
<h2>4</h2>
<h2>5</h2>
<h2>6</h2>
</div>
i prefer to use ":eq" even ":nth-of-type". So will be :
$('.books_inarticle_list').insertBefore('#content_column > h2:eq('+($('#content_column > h2').length()-2)+')');

What is the difference between the selectors #id and [id$='id']?

What is the difference between two statements:
$("span[id$='id']").text(var);
// And
$("#id").text(var);
HTML code is : <span class="normal11" id="id"></span>
The first one is using ends with selector while the second one is using just normal id selector.
Attribute Ends With Selector [name$="value"]
ID Selector ("#id")
By the documentation on JQuery:
$("#id") uses the JavaScript function document.getElementById(), which is extremely efficient. Link.
So, the second way should be faster and should be used.
Some different between id selector and attribute selector is
Since id selector called document.getElementById(),
it only return the first element that have a id equal to that.
However, if you use attribute selector, it will return all elements that have the id attribute that equals to that.
But duplicated id is actually invalid in HTML, and should never used.
if you really want to do that, use class instead.
example
$("#id-selector").click(function(){
$("#test").css("color", "red");
});
$("#attr-selector").click(function(){
$("*[id=test]").css("color", "blue");
});
http://jsfiddle.net/toucyqas/1/

jQuery selector to find the last element

I will really appreciate if someone can tell me how this might be possible.
If I have the following html,
<span><hr class=​"tierEnd">​</span>
<span><hr class=​"tierEnd">​</span>
<span><hr class=​"tierEnd">​</span>
<span><hr class=​"tierEnd">​</span>
How can I select the last hr element?
Tried with last-child, last, last-of-type already
Use jquery :last selector
$(".tierEnd:last")
Use :last or .last()
$('hr:last')
or
$('hr').last()
Demo
last-child and last-of-type does not work in case of <hr>
In that case use $('span:last-of-type hr')
You may use the .last() jQuery method:
$(".tierEnd").last()
For some reason, it is thought to be faster than the pseudo selector.
jQuery("span > .tierEnd").last()
or
jQuery("span > .tierEnd:last")
Using span > .tierEnd will only select direct descendants of a span tag with tierEnd class
You should use the below selector to get the last <hr> element.
jQuery("span:last-child hr.tierEnd")
Please like if this helps you! Cheers :)

jQuery opposite of "starts with" selector: [^=]

I have some div tag below:
<div class="magazine"></div>
<div class="newsletter"></div> // I need to take this div
<div class="may-moon"></div>
If I needed div with class start with "ma", I would use $('div[class^="ma"]'), but what is opposite? thanks.
The opposite would be to use jQuery :not():
$('div:not([class^="ma"])')
You can use the negative filtering function "not" like this: $('div').not('[class^="ma"]'), or the negative selector ":not" like this: $('div:not([class^="ma"])') (as pointed by Karl-André Gagnon)
You need to use :not() Selector for this. because there is no exact opposite selector exist of [^=] and * in jquery.
:not() Selector - Selects all elements that do not match the given selector.
See more about Jquery selectors
There a opposite selector exist ! -
Attribute Not Equal Selector [name!="value"] - Select elements that either don’t have the specified attribute, or do have the specified attribute but not with a certain value.
but use of this ! selector, you need to provide full-name of class.
$('div[class!="magazine"][class!="may-moon"]')
Try This

Selecting all but the first child of parent with an ID and then applying action

I want to select all the child elements of a parent element (except the first) with jQuery and I have the below..
$("li:not(:first-child)");
But I'm not sure how I can apply it to just the certain parent ID, would something like this work?
$('#myID').("li:not(:first-child)");
If so, I then want to add an element before the respective <li> tag. Would I then be able to do this with?
$('#myID').("li:not(:first-child)").before('<li>Test</li>');
I'm guessing something above is wrong as it isn't working.
Close, just pass in the selector context:
$("li:not(:first-child)", "#myID")
http://api.jquery.com/jQuery/
jQuery( selector [, context] )
selector: A string containing a selector expression
context: A DOM Element, Document, or jQuery to use as context
EDIT:
My initial answer assumed that you have no more li within the child's li. if you strictly only wants to select the children, use >:
$("#myID > li:not(:first-child)")
There's different solutions:
$("li:not(:first-child)", "#myID"); // see #SiGanteng answer
$("#myID li:not(:first-child)");
$("#myID").find("li:not(:first-child)");
Simple: using the :gt() help selector:
Just do it like: demo fiddle
$("#myID li:gt(0)").before('<li>Test</li>');
If you are concerned about speed :) :
$("#myID").find("li:gt(0)").before('<li>Test</li>');
or like: demo fiddle
$("#myID li:not(:first-child)").before('<li>Test</li>');
Assuming #myID is a ul or ol element, another possible way to get all children but the first is
$('#myID').children().slice(1)

Categories

Resources