2. Review of Selection
There several ways of selecting
elements in jQuery, a few are listed
below
There several ways of selecting elements in
jQuery, a few are listed below:
<ul>
$(‘> p’)
$(‘li:not(‘li.selected’)’)
$(‘li:first’)
$(‘li.since ~ li’)
$(‘h2 + div’)
</ul>
Consider Selecting lists element after
‘li.selected’, we could simple use
e.t.c.
<li>First item</li>
<li class="selected">Second item</li>
<li>Third item</li>
<li>Fourth item</li>
<li>Fifth item</li>
$(‘li.selected’).nextAll(‘li’)
OR
$(‘li.selected ~ li’)
3. More Examples
Consider selecting all the elements of a
div as in
<div id=“content”>
…
...
…
</div>
From the example at the side,
Some of the methods that be used are
$(‘> *’,’#content’);
$(‘#content’).children()
$(‘#content’).find(‘> *’)
Question: Which is faster?
5. Selecting with Regular Expressions
Consider Selecting the ‘p’ tag which contains the word greetings
<p>Hello Emmanuel greetings</p>
<p>Hello Emmanuel, greetings to you</p>
<p>greetings to you Emmanuel</p>
<p>Hello Emmanuel</p>
var count = $('p').filter(function(){
return $(this).text().match(/(^|s)?.*greeting*/);
});
6. Advice
Use an ID if Possible (uniqueness)
$(‘#content’)
Avoid Selecting by Class Only (may fast on modern browsers but slow on old browsers)
$(‘.span12’)
KISS ( Keep it Simply Simple)
$("body #page:first-child article.main p#intro em");
OR
$("p#intro em");
$(‘p’).find(‘#into em’)
Increase Specificity from Left to Right
Avoid Selector Repetition
$("p").css({"color":"blue“,}).text();
$("p").css("font-size", "1.2em");
$("p").text("Text changed!");