Reputation: 75
$('li[data-number=4]').after().hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-number="0">1</li>
<li data-number="1">2</li>
<li data-number="2">3</li>
<li data-number="3">4</li>
<li data-number="4">5</li>
<li data-number="5">6</li>
<li data-number="6">7</li>
<li data-number="7">8</li>
</ul>
I want to hide all element after data-number 4 and want to get first hidden li number. The output will 5. How can I achieve this? Please help me.
Upvotes: 0
Views: 785
Reputation: 117
Please check this:
$('li[data-number=4]').nextAll().hide();
var firstHiddenLiNumber = $('li[data-number=4]').next().data('number');
console.log(firstHiddenLiNumber);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-number="0">1</li>
<li data-number="1">2</li>
<li data-number="2">3</li>
<li data-number="3">4</li>
<li data-number="4">5</li>
<li data-number="5">6</li>
<li data-number="6">7</li>
<li data-number="7">8</li>
</ul>
Upvotes: 0
Reputation: 1214
If its simple, why not use a loop? Get a an each loop going through all list iteams $(ul li).each(); then we can access the data- values
Upvotes: 0
Reputation: 3334
You can use the following js code to achieve your purpose in single line..!
Instead of using after()
method you need to use nextAll()
method.
var firstHidden = $('[data-number=4]').nextAll().hide().first();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-number="0">1</li>
<li data-number="1">2</li>
<li data-number="2">3</li>
<li data-number="3">4</li>
<li data-number="4">5</li>
<li data-number="5">6</li>
<li data-number="6">7</li>
<li data-number="7">8</li>
</ul>
Upvotes: 0
Reputation: 880
$('li:gt(4)').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-number="0">1</li>
<li data-number="1">2</li>
<li data-number="2">3</li>
<li data-number="3">4</li>
<li data-number="4">5</li>
<li data-number="5">6</li>
<li data-number="6">7</li>
<li data-number="7">8</li>
</ul>
you can use just $('li:gt(4)').hide();
Upvotes: 0
Reputation: 16506
.after()
means: Insert content, specified by the parameter, after each element in the set of matched elements. API
What you want instead is .nextAll()
: Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. API
So your code becomes:
$('li[data-number=4]').nextAll().hide();
To get the first hidden, use $('li:hidden').first()
. Docs for :hidden
and .first()
: http://api.jquery.com/hide/, https://api.jquery.com/first/
Upvotes: 1