There are several way to find the HTML element using jquery. Below is example that most used for me.
1) Find Parent Element
Question : How to find parent element where have ‘sub’ classname?
Example, i have html like this :
<ul class='top'> <li>one</li> <li>two</li> <li>three</li> <li>four <ul class='sub'> <li>four.one</li> <li>four.two</li> <li> <a href='#' class='sclick'>four.three</a> </li> </ul> </li> </ul>
Answer :
So, in jquery we must add the following script :
$(function() { $('.sclick').click(function(){ console.log($(this).parent().parent('ul.sub').length); // Result is 1 }); });
2) Find Previous and Next Element
Question : How to find previous and next element of li, How?
<ul class='top'> <li>one</li> <li>two</li> <li>three</li> <li>four <ul class='sub'> <li>four.one</li> <li>four.two</li> <li> <a href='#' class='sclick'>four.three</a> </li> <li>four.four</li> </ul> </li> </ul>
Answer :
To find prev and next element, you must add the following script :
$(function() { $('.sclick').click(function(){ console.log($(this).parent().next().html()); // Result is four.four console.log($(this).parent().next().length); // Result is 1 console.log($(this).parent().prev().html()); // Result is four.two console.log($(this).parent().prev().length); // Result is 1 }); });
3) Find All Element of Li (Include Children too)
Example, i have HTML structure of <li> like this :
Script in HTML :
<ul class='top'> <li>one</li> <li>two</li> <li>three</li> <li>four <ul class='sub'> <li>four.one</li> <li>four.two</li> <li>four.three <ul> <li>four.1</li> <li>four.2</li> <li>four.3</li> </ul> </li> </ul> </li> </ul>
To find all element of li (include the parent and children), we can use the each() function, like this :
$(function() { $('ul li').each(function(i,v){ // li have children <ul> if($(this).find('ul').length > 0){ // get last li that have children liText = $(v).contents().first(); console.log(liText.text().trim()); } // li not have children else{ console.log($(v).text()); } }); });
4) Find First level of Li without children
Script in HTML like this :
<ul id="nav"> <li>menu 1</li> <li>menu 2 <ul id="subnav"> <li>sub 1</li> <li>sub 2</li> <li>sub 3</li> </ul> </li> <li>menu 3</li> <li>menu 4</li> <li>menu 5</li> <li>menu 6</li> </ul>
To get the first element li without the children, use this script :
$(function() { $("ul:eq(0) > li").each(function(i, n){ firstLi = $(n).contents().first(); console.log(firstLi.text().trim()); }); });
Or :
$(function() { $("#nav > li").each(function(i, n){ firstLi = $(n).contents().first(); console.log(firstLi.text().trim()); }); });
— end —