How to check if the element is not the first-child?
How do you know if the current element is not the first-child?
It should work with $(this)
, for example:
$("li").click开发者_开发技巧(function(e) {
if (/* $(this) is not the first-child */)
{
/* do something */
}
});
You can do this just to test an element if it's the first child: $(this).is(':first-child')
. Other selectors like :last-child
would work too.
You could simply ask for its .index()
position (relative to its siblings).
$(this).index(); // returns a zero based index position
For all li
's in #thing
that aren't first child:
$('#thing li:not(:first-child)')
see http://api.jquery.com/not-selector/
If you would like to select everything except the first child, this is how to do it:
$('#some-parent').children().not(':first')
Also, you can check if $(this).prev().length
is defined, like in:
if (!$(this).prev().length){ //This means $(this is the first child
//do stuff
}
Check the index
$(this).index() == 0 // is first
Keep it simple, use the DOM
$("li").click(function(e) {
if (this.previousSibling != null)
{
/* do something */
}
});
For people who want a vanilla JS solution:
<div id="parent">
<div id="child-1"></div>
<div id="child-2"></div>
<div id="child-3"></div>
</div>
let element = document.getElementById('child-1');
console.log(element.parentElement.firstElementChild === element); // true
console.log(element.parentElement.lastElementChild === element); // false
element = document.getElementById('child-2');
console.log(element.parentElement.firstElementChild === element); // false
console.log(element.parentElement.lastElementChild === element); // false
element = document.getElementById('child-3');
console.log(element.parentElement.firstElementChild === element); // false
console.log(element.parentElement.lastElementChild === element); // true
It's not the most elegant thing but it gets the job done.
You can even check if it's the nth element in the same fashion.
let n = 2; // check if it's the 2nd child
let element = document.getElementById('child-2');
// index starts at 0
console.log(element.parentElement.children[-1 + n] === element); // true
jQuery .not()
$(this).not(':first');
$("li").click(function(e) {
if ($(this).index != 0 )
{
/* do something */
}
});
A less complex (IE 9 compatible) pure/vanilla JavaScript way to achieve this is to use the matches
function of Element
. See https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
Example:
console.log( document.querySelectoer( '#my-div' ).matches( ':first-child' ) ); // true or false
精彩评论