How check in javascript that a li element has inner ul? - javascript

Good day.
HTML:
<ul>
<li class="sub">catalog
<ul>
<li class="dir">subcatalog
<ul>
<li>sublink</li>
<li>sublink</li>
<li>sublink</li>
</ul>
</li>
<li class="dir">subcatalog</li>
<li class="dir">subcatalog</li>
</ul>
</li>
<li class="sub">catalog</li>
<li class="sub">catalog</li>
<li class="sub">catalog</li>
<li class="sub">catalog</li>
</ul>
<style>
ul > li.sub:hover > ul{display:block;}
ul > li.sub:hover{
background: #fff url(../../images/arrow1.png) no-repeat 91% center;
border-bottom: 2px solid #e30613;
padding-right: 25px;
}
</style>
I use script:
$('li.main_menu_top_li').has('ul').addClass('sub');
Tell me please how make it on javascript (only javascript)?

One of two ways.
first get the element:
var d = document.getElementByClassName("li.main_menu_top_li");
Then:
if (d.firstChild) {
// It has at least one
d.className = d.className + " sub";
}
or the hasChildNodes() function:
if (element.hasChildNodes()) {
// It has at least one
d.className = d.className + " sub";
}

Assuming you want to add the sub class to the LI that has nested ULs under it:
Plain JS
var li = document.querySelector('li.main_menu_top_li');
if (li.getElementsByTagName("ul").length>0) li.className+="sub";
// or get the addClass/hasClass from http://snipplr.com/view/3561/
jQuery:
var li = $('li.main_menu_top_li');
if (li.children('ul').length) li.addClass('sub');
If you want to add the class to any UL that is inside an LI then
var li = $('li.main_menu_top_li');
li.children('ul').each(function() {
$(this).addClass('sub');
});

The following code looks at all LI elements and checks if they have a UL element. If so, that UL element gets the class 'sub'. If you want instead for that LI to have the class 'sub', un-comment the commented portions of code and then remove the line underneath each commented line.
Here's the first jsfiddle:
//IE 10+ and all other major browsers
var el = document.getElementsByTagName('li');
var listItems = Array.prototype.slice.call(el);
listItems.forEach(function(el) {
var childrenList = Array.prototype.slice.call(el.children);
childrenList.forEach(function(el) {
if(el.tagName === 'UL') {
//if(!el.parentNode.classList.contains('sub') {
if(!el.classList.contains('sub')) {
//el.parentNode.classList.add('sub')
el.classList.add('sub');
}
}
});
});
Here's the second jsfiddle:
//IE8+ and all other major browsers, I think
var el = document.getElementsByTagName('li');
var listItems = Array.prototype.slice.call(el);
listItems.forEach(function(el) {
var childrenList = Array.prototype.slice.call(el.children);
childrenList.forEach(function(el) {
if(el.tagName === 'UL') {
//if(el.parentNode.className === '') {
if(el.className === '') {
//el.parentNode.className = 'sub'
el.className = 'sub';
} else {
//el.parentNode.className += 'sub'
el.className += ' sub';
}
}
});
});

Related

How to remove <li> list items and make the remaining ones change their position and id?

Tricky question and far too advanced for my level (js student).
Lets say I use the append method to generate <li> items inside an <ol>, and I need each one of those li items to have a unique id, so I thought to get the amount of <li> (length) items I generated by saying this : var index = document.getElementById("ol1").getElementsByTagName("li").length+1; and use this number to create unique id's for every item I generate by doing this: li.id="li"+index; so the first one I generate becomes #li1 (since the amount of li items is one), the next one #li2 and so on. *btw, is it the right approach to do this?
Now lets say I want to remove #li1, then #li2 would replace it in position 1 of the list, but its id will still be #li2 since it has gotten it already.
For example what I ultimately want is when I remove #li1, then #li2 becomes #li1, #li3 becomes #li2, #li4 becomes #li3.....and so on.
What would be the right logic approach to do such a gimmick?
function append() {
var index = document.getElementById("ol1").getElementsByTagName("li").length + 1;
var ol = document.getElementById("ol1");
var li = document.createElement("li");
li.id = "li" + index;
li.innerHTML = (`LIST ITEM <input value=this is id: #li${index}><button class=remove id= button${index} onclick=remove${index}()>REMOVE</button>`);
ol.append(li)
}
function remove1() {
var rem = document.getElementById("li1");
rem.remove();
}
function displayIndex() {
var index = document.getElementById("ol1").getElementsByTagName("li").length;
alert(index);
}
#li1 {
color: red;
}
#li2 {
color: green;
}
#li3 {
color: blue;
}
ol button {
color: red;
visibility: hidden;
}
#button1 {
color: red;
visibility: visible;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<button id="btn1" onclick="append()">Append</button>
<button id="btn2" onclick="displayIndex()">Index</button>
</head>
<body>
<ol id="ol1">
</ol>
</body>
</html>
First off:
There are no "right" approaches. Only working implementations. How it is achieved might differ from developer to developer, and as long as it works, it should be considered the "right" way (however, not necessarily the most efficient or optimized or any other way).
One way would be to use a remove() function that re-assigns the ID's of the remaining <li>s (after the removal, obviously) as a side-effect.
function removeItemOf(list, listItem) {
if (!list.contains(listItem)) return;
listItem.remove();
indexItemsOf(list);
// For displaying the removed ID on-screen
document.querySelector('div').append(
document.createElement('br'),
document.createTextNode(`Removed <li> with id '${listItem.id}'`)
);
}
function indexItemsOf(list) {
for (var i = 0; list.children[i]; ++i) {
list.children[i].id = (list.id || list.tagName) + '-li' + i;
// For displaying the <li>'s ID on-screen
list.children[i].textContent = `With ID '${list.children[i].id}'`;
}
}
var list = document.querySelector('ol');
indexItemsOf(list);
setTimeout(() => {
removeItemOf(list, list.children[0]);
}, 2000);
setTimeout(() => {
removeItemOf(list, list.children[1]);
}, 4000);
<ol>
<li></li>
<li></li>
<li></li>
<li></li>
</ol>
<div></div>
However, re-assigning a previously used ID makes it not unique to one element, as it now identifies another element it hasn't identified before. For environments where this would be important (e.g. relying on an element to reference certain other elements, or to have a certain event-listener, etc.), re-using an ID would break the environment.
To circumvent this problem, one could keep track of how many unique items a list had over its entire lifetime, and create the next item with an ID using that amount, and then increase the amount by one.
Here is an example:
var list = document.querySelector('ol');
list.uniqueItems = 0;
// Here: Using Event-Delegation for removing a <li>
list.addEventListener('click', function(evt) {
if (evt.target.classList.contains('btn-delete'))
evt.target.closest('li').remove();
});
document.querySelector('button').addEventListener('click', function() {
var item = document.createElement('li');
item.id = 'li-' + list.uniqueItems;
item.textContent = `Has the ID '${item.id}' `;
var btnDelete = document.createElement('button');
btnDelete.classList.add('btn-delete');
btnDelete.textContent = 'Delete Item';
item.append(btnDelete);
list.append(item);
list.uniqueItems++;
});
<button>New Item</button>
<ol></ol>
You can just loop through each list item after your remove one and regenerate the IDs for each.
ol = document.getElementById("ol1");
function indexLIs(){
i = 1;
ol.querySelectorAll("li").forEach(function(li){
id = "li" + i;
li.setAttribute("id",id);
li.querySelector("input").value = "this is id: #" + id;
i++;
});
}
function append() {
var index = document.getElementById("ol1").getElementsByTagName("li").length + 1;
var li = document.createElement("li");
li.id = "li" + index;
li.innerHTML = (`LIST ITEM <input value=this is id: #li${index}><button class=remove id= button${index} onclick=remove${index}()>REMOVE</button>`);
ol.append(li)
}
function remove1() {
var rem = document.getElementById("li1");
rem.remove();
indexLIs();
}
function displayIndex() {
var index = document.getElementById("ol1").getElementsByTagName("li").length;
alert(index);
}
#ol1 li:nth-child(1) {
color: red;
}
#ol1 li:nth-child(2) {
color: green;
}
#ol1 li:nth-child(3) {
color: blue;
}
ol button {
color: red;
visibility: hidden;
}
#button1 {
color: red;
visibility: visible;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<button id="btn1" onclick="append()">Append</button>
<button id="btn2" onclick="displayIndex()">Index</button>
</head>
<body>
<ol id="ol1">
</ol>
</body>
</html>
Your approach is fine. It would be easier for you to keep counting from the last element without changing the other elements even if you remove an element. In that situation use a global variable and initialize it with the length of your initial list. Something like that should do the work:
var index = 1; // or the index you wish to start from
function append(){
var ol = document.getElementById("ol1");
var li = document.createElement("li");
li.id="li"+index;
li.innerHTML = (`LIST ITEM <input value=this is id: #li${index}><button class=remove id= button${index} onclick=remove${index}()>REMOVE</button>`);
ol.append(li);
// now we will increment our index for the next iteration
index++;
}
Hope this was useful.

How to use closest() in a proper way in js

Student here!
Lets say i have function append() which generates <li> items inside an <ol>,those li items contain 2 buttons,one for removing the <li> that lies within and one for creating the same item but inside itself this time,in order to make another list layer.
Both by using the closest() method.
i cant figure out how to use the ADD <button>,i can call it but i cannot it make it work the way i want to.
I get this :
But i want to get something like this :
this is how i'm trying to do it :
function append() {
var ol = document.getElementById("ol1");
var li = document.createElement("li");
li.innerHTML = (`LIST ITEM <input class=input><button class=add>ADD</button><button class=remove>REMOVE</button>`);
ol.append(li)
document.getElementById("ol1").addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.classList.contains("remove")) tgt.closest("li").remove();
if (tgt.classList.contains("add")) tgt.closest("li").appendChild(li);
})
}
<html>
<body>
<button id="btn1" onclick="append()">Append</button>
<ol id="ol1">
</ol>
</body>
</html>
To number with 1., 1.1, 1.2, 2., 2.1, 3., you need to use CSS. The counters function, obtains the number of the li. Each time an ol appears, the counter is reset to 1.. When a li appears, the top counter is used, concatenated with the new next new number of the previous li.
ol {
counter-reset: item
}
li {
display: block;
}
li:before {
content: counters(item, ".") ". ";
counter-increment: item;
}
In the append function, we add the li... For this, we call another function, which we will call create_li() which does the creation of the li.
function append() {
document.querySelector("#ol1").append( create_li() )
}
In the create_li() function, we create the li and return it with return li. In li, we add the two button elements, add and remove, but instead of doing it through a string, we do it with the function we already know, that is to say, document.createElement(), and also, on each button, we can add una funciĆ³n que llamaremos button_click function, used to receive the click event through addEventListener.
function create_li(){
var li = document.createElement("li")
var add = document.createElement("button")
var remove = document.createElement("button")
li.innerHTML = "LIST ITEM <input class=input>"
add.className = "add"
remove.className = "remove"
add.innerHTML = "+"
remove.innerHTML = "-"
add.addEventListener("click",button_click)
remove.addEventListener("click",button_click)
li.appendChild(add)
li.appendChild(remove)
return li
}
The button_click function, what it does is create the ol and li structure. In addition, it detects if the button clicked is the add or remove.
function button_click(e) {
const tgt = e.target;
var litg = tgt.closest("li")
var oltg = litg.querySelector("ol")
if(oltg==null){
var ol = document.createElement("ol")
litg.appendChild(ol)
oltg = ol
}
if (tgt.classList.contains("remove")){
litg.remove()
}
if (tgt.classList.contains("add")){
oltg.appendChild( create_li() )
}
}
The HTML structure is based on the li has to be inside the ol, and each sublist has to have an ol inside the li.
<ol>
<li>
1.
<ol>
<li>1.1</li>
<li>1.2</li>
<li>1.3</li>
</ol>
</li>
<li>
2.
<ol>
<li>2.1</li>
<li>2.2</li>
<li>2.3</li>
</ol>
</li>
<li>
3.
<ol>
<li>3.1</li>
<li>3.2</li>
<li>3.3</li>
</ol>
</li>
</ol>
Finished code:
function button_click(e) {
const tgt = e.target;
var litg = tgt.closest("li")
var oltg = litg.querySelector("ol")
if(oltg==null){
var ol = document.createElement("ol")
litg.appendChild(ol)
oltg = ol
}
if (tgt.classList.contains("remove")){
litg.remove()
}
if (tgt.classList.contains("add")){
oltg.appendChild( create_li() )
}
}
function create_li(){
var li = document.createElement("li")
var add = document.createElement("button")
var remove = document.createElement("button")
li.innerHTML = "LIST ITEM <input class=input>"
add.className = "add"
remove.className = "remove"
add.innerHTML = "+"
remove.innerHTML = "-"
add.addEventListener("click",button_click)
remove.addEventListener("click",button_click)
li.appendChild(add)
li.appendChild(remove)
return li
}
function append() {
document.querySelector("#ol1").append( create_li() )
}
ol {
counter-reset: item
}
li {
display: block;
}
li:before {
content: counters(item, ".") ". ";
counter-increment: item;
}
<button id="btn1" onclick="append()">Append</button>
<ol id="ol1"></ol>
This is probably what you want?
function append() {
var ol = document.getElementById("ol1");
var li = document.createElement("li");
li.innerHTML = (`LIST ITEM <input class="input"><button class="add" onclick="add(this)">ADD</button><button class="remove" onclick="remove(this)">REMOVE</button><ol></ol>`);
ol.append(li)
}
function add(e) {
var li = document.createElement("li");
li.innerHTML = (`LIST ITEM <input class="input"><button class="add" onclick="add(this)">ADD</button><button class="remove" onclick="remove(this)">REMOVE</button><ol></ol>`);
e.parentElement.getElementsByTagName("ol")[0].appendChild(li);
}
function remove(e) {
e.parentElement.parentElement.removeChild(e.parentElement);
}
<html>
<body>
<button id="btn1" onclick="append()">Append</button>
<ol id="ol1">
</ol>
</body>
</html>
Instead of using 'closest' in the add method, you can simply find the parent and append in that.
EG : tgt.parentNode().appendchild(childLi)

Appending elements through JavaScript for dynamically generated id

<li class="list" id='+id+'>
<a class="anchor" id='+id+' href='#stay' onClick="getValue(this);" style="text-decoration: none, color:red">hello</a>
Now inside JavaScript:
listElem=listElem+'<li class="list" style="height: 18px; display: inline- block;width:100px;line-height: 20px;padding-right:25px;"><a class="anchor" id=""+results+"" href="#stay" style="width:1028px;">"+results+"</a> </li>';
Now I need to append the listElem after li tag. Since id is dynamically generated.
How could I append it through innerHTML or html()?
How could I pass id here: $( "" ).html(listElem); or is here any other method?
You're probably looking for jQuery's insertAfter() and prop() methods.
If, say you have your HTML code in a a variable listItem, you can convert it to jQuery object, use prop() to set id and then insertAfter() to place it the last <li> element with a class="list":
var listElem = jQuery('<li class="list" style="height: 18px; display: inline-block;width:100px;line-height: 20px;padding-right:25px;"><a class="anchor" id=""+results+"" href="#stay" style="width:1028px;">"+results+"</a></li>');
listElem.prop('id', id).insertAfter('li.list:last');
If I understand your question correctly, then jQuery provides the before method of jQuery objects. To append listElem before the li element, you could call
$('#+id+').before(listElem);
you can do like this on click event
<li class="list" id='+id+' onclick='getvalue(this)'>
<a class="anchor" id='+id+' href='#stay' onClick="getValue(this);" style="text-decoration: none, color:red">hello</a>
jQuery code:
function getvalue(elem){
var listElem='<li class="list" style="height: 18px; display: inline- block;width:100px;line-height: 20px;padding-right:25px;"><a class="anchor" id=""+results+"" href="#stay" style="width:1028px;">"+results+"</a> </li>';
var id=$(elem).attr('id');
$('#'+id).html(listElem);//your code
}
Here is an option:
var ul = document.querySelector('ul');
var li1 = makeLi();
var li2 = makeLi();
var li3 = makeLi();
insert(ul, li2); // insert #my-uid-2
insert(ul, li1); // insert #my-uid-1
insert(ul, li3); // insert #my-uid-3
function uid () {
var i = 1;
return (this.uid = function () {
return 'my-uid-' + (i++);
})();
};
function makeLi () {
var re = /\+id\+/g;
var ul = document.createElement('ul');
var li = '<li id="+id+">#+id+</li>';
return (this.makeLi = function () {
ul.innerHTML = li.replace(re, uid());
return ul.firstChild;
})();
}
function insert (ul, li) {
var child;
var i = 0;
var re = /^.*?(\d+)$/;
var n = +li.id.replace(re, '$1');
var children = ul.childNodes;
while (
(child = children[i]) &&
n > +child.id.replace(re, '$1')
) i++;
if (child) ul.insertBefore(li, child)
else ul.appendChild(li);
}
#my-uid-1 {
background: yellow;
}
#my-uid-2 {
background: orange;
}
#my-uid-3 {
background: red;
}
<ul></ul>

Wrap navigation in a subnavigation

I have a dynamically created navigation, where i can not make parent/child list for navigation.
I want to add a link named "More..." at the end of the list, according to available space. And then show all remaining elements as child of More...
For example if i have elements list1, list2, list3, ..... list10.
It will be displayed as list1, list2, list3, more... and rest of the links will be child of more...
I tried creating a script for this, and i think i am very close. But i have following 2 issues:
How to add UL around child list.
Sometimes "More..." is broken to next line.
Following is my JS code:
$(document).ready(function() {
var nav = $('ul');
var more = '<li>More...</li>';
nav.prepend( more );
var availableSpace = nav.innerWidth();
var list = 0;
var countedSpace = 0;
$('li').each(function(){
var current = $(this);
countedSpace = countedSpace+current.outerWidth();
if (countedSpace < availableSpace) {
list++;
}
})
var showInList = list; //Space available for xx no. of items.
var newList = [];
// Start at 2, don't include dynamically added more link.
for (i = 2; i < showInList; i++) {
newList.push($(nav).find("li:nth-child("+i+")"));
}
newList.push(more);
var childList = [];
for (i = showInList; i <= nav.children().length; i++) {
childList.push($(nav).find("li:nth-child("+i+")"));
}
//nav.empty();
nav.html(newList);
$(nav).find("li:last-child").append(childList);
});
jsfiddle: http://jsfiddle.net/alokjain_lucky/Lhh019ru/
1. How to add UL around child list.
Try creating a jquery UL object and then appending the li items to it. Like this:
var ulChildren = $("<ul/>").append(childList);
$(nav).find("li:last-child").append(ulChildren);
2. Sometimes "More..." is broken to next line.
This is happening because the li children are visible and stacking to the right, try adding
li ul{
display:none;
}
to test the correct layout, after step 1.
Here is an example of the above on JSFiddle, click on "More..." to toggle children visibility
Example code
I think this will accomplish what you're looking for:
var availableWidth= $('ul').innerWidth();
var totalWidth= $('<li class="more">More</li>').appendTo($('ul')).outerWidth();
$('li').each(function(index) {
totalWidth+= $(this).outerWidth();
if(totalWidth >= availableWidth) {
$('ul li:eq('+(index-2)+')').after(
$('.more').click(function() {
$('ul li:gt('+(index-1)+')').toggle()
})
);
$('ul li:gt('+(index-1)+')').css({
display: 'none'
});
return false;
}
});
var availableWidth= $('ul').innerWidth();
var totalWidth= $('<li class="more">More</li>').appendTo($('ul')).outerWidth();
$('li').each(function(index) {
totalWidth+= $(this).outerWidth();
if(totalWidth >= availableWidth) {
$('ul li:eq('+(index-2)+')').after(
$('.more').click(function() {
$('ul li:gt('+(index-1)+')').toggle()
})
);
$('ul li:gt('+(index-1)+')').css({
display: 'none'
});
return false;
}
});
ul {
padding:0px;
margin:0px;
border:1px solid #ccc;
overflow:hidden;
width: 500px;
}
li {
list-style:none;
float:left;
margin:10px;
border:1px solid #f1f1f1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>a Home</li>
<li>b Services</li>
<li>c Meet our team</li>
<li>d work process</li>
<li>e About us</li>
<li>f Contact us</li>
<li>g Meet out team</li>
<li>h work process</li>
<li>i About us</li>
<li>j Contact us</li>
</ul>
totalWidth is initialized as the width of the More list item. I gave it a class of more, so it could be referred to within each.
When totalWidth is greater-or-equal-to availableWidth, .more is inserted in the appropriate position (index) of the ul.
The click handler toggles the display of list items at higher positions. Those higher-positioned list items are then hidden.
return false prevents each from continuing to run once this is done.

Hiding list items with a "show more" button

I have an issue. I am getting data from a MySQL database, and make a list of it. That's all good, and works fine, but the list is now over 100 items long if I don't limit it.
I've tried Googling how to shorten list, and found some things with jQuery and JavaScript, but that didn't work too well.
What I'm looking for is a way to make the list limit itself on 10 items, with a [More] button under it. When pressed, the next 10 items show, and when pressed again, 10 more etc.
I have my list in normal <li> and <ul> bits.
If there's any more information needed, please ask me. This is the webpage it's about: http://lolmewn.nl/stats/
A bit of my PHP code:
echo "<li><a href=\"?player=" . $row['player'] . "\">" . $row['player'] .
"</a></li>\n";
Maybe you can try this. In this example I used 2 items instead of 10. I used css to hide all li elements starting from the 3rd li element inside the ul. I used jQuery to reveal additional 2 lis every time show more is clicked.
Hope this helps
Updated Link Again...
EDIT
$(function () {
$('span').click(function () {
$('#datalist li:hidden').slice(0, 2).show();
if ($('#datalist li').length == $('#datalist li:visible').length) {
$('span ').hide();
}
});
});
ul li:nth-child(n+3) {
display:none;
}
ul li {
border: 1px solid #aaa;
}
span {
cursor: pointer;
color: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<ul id="datalist">
<li>dataset1</li>
<li>dataset1</li>
<li>dataset2</li>
<li>dataset2</li>
<li>dataset3</li>
<li>dataset3</li>
<li>dataset4</li>
<li>dataset4</li>
<li>dataset5</li>
<li>dataset5</li>
</ul>
<span>readmore</span>
One method is to use ajax to load the list items & restrict them to 10 items using mysql limit.
Otherwise, if you load all at once, you can do the following: (write the code yourself)
Load all of them in a ul and make the display of all none.
Then using jquery eq selector display the first 10 li elements.
on clicking more, just toggle those li which you want to display.
If you want this is pure javascript I made a example on jsfiddle
Javascript
function showMore() {
var listData = Array.prototype.slice.call(document.querySelectorAll('#dataList li:not(.shown)')).slice(0, 3);
for (var i=0; i < listData.length; i++)
{
listData[i].className = 'shown';
}
switchButtons();
}
function showLess() {
var listData = Array.prototype.slice.call(document.querySelectorAll('#dataList li:not(.hidden)')).slice(-3);
for (var i=0; i < listData.length; i++)
{
listData[i].className = 'hidden';
}
switchButtons();
}
function switchButtons() {
var hiddenElements = Array.prototype.slice.call(document.querySelectorAll('#dataList li:not(.shown)'));
if(hiddenElements.length == 0)
{
document.getElementById('moreButton').style.display = 'none';
}
else
{
document.getElementById('moreButton').style.display = 'block';
}
var shownElements = Array.prototype.slice.call(document.querySelectorAll('#dataList li:not(.hidden)'));
if(shownElements.length == 0)
{
document.getElementById('lessButton').style.display = 'none';
}
else
{
document.getElementById('lessButton').style.display = 'block';
}
}
onload= function(){
showMore();
}
HTML
<ul id="dataList">
<li class="hidden">One</li>
<li class="hidden">Two</li>
<li class="hidden">Three</li>
<li class="hidden">Four</li>
<li class="hidden">Five</li>
<li class="hidden">Six</li>
<li class="hidden">Seven</li>
<li class="hidden">Eight</li>
<li class="hidden">Nine</li>
<li class="hidden">Ten</li>
<li class="hidden">Eleven</li>
</ul>
<input id="moreButton" type="button" value="More" onclick="showMore()"/>
<input id="lessButton" type="button" value="Less" onclick="showLess()"/>
CSS
.shown{
display:block;
}
.hidden{
display:none;
}
Have you ever try jquery datatable yet?
Simple solution in pure javascript:
var ul = document.getElementsByTagName("ul")[0], //Your <ul>
readmore = document.createElement("li"),
lisColl = ul.getElementsByTagName("li"),
len = lisColl.length,
lis = [],
pos = 0;
readmore.textContent = "Read more";
for (var i = 0; i < len; i++) {
lisColl[i].style.display = "none";
lis.push(lisColl[i]);
}
readmore.onclick = function () {
if (this.parentNode) {
this.parentNode.removeChild(this);
}
for (var c = 0; pos < len; pos++) {
if ((c++) === 10) {
ul.insertBefore(this, lis[pos + 1]);
break;
}
lis[pos].style.display = "";
}
}
readmore.onclick.call(readmore);
If you want to limit the number of results from the database, add LIMIT 10 (or any number) to the MySQL query.
If you want to actually hide the lists, but leave them available, you will need CSS to initially hide them, and Javascript/Jquery to unhide them. (CSS3 might let you unhide them without Javascript/Jquery, but it isn't fully supported everywhere yet).
Assuming all the list items have the same CSS class then a javascript loop like the following may work:
function unhide(number) {
var items = document.getElementsByClassName('tagnamehere');
var shown=0;
for (var i=0; shown<number && i<items.length; i++) {
if (items[i].style.display=="" || items[i].style.display=="none") {
items[i].style.display="list-item";
shown+=1;
}
}
}
In the CSS, all you need to add is .tagnamehere {display:none;}
Feel free to substitute with your own tags.

Categories

Resources