'Jquery nested LI elements inside tabbed content UL LI list
Im using tabbed content on my page (SEE MY FIDDLE)
Now the tabbed content makes use of <ul><li>
elements to display the different tabs. Inside one of these tabs I would like to add a <ul><li>
list however the list is not getting displayed correctly I suspect because:
- The jquery is effecting it
- It is nested inside another li elements
Any idea how I can fix this?
Solution 1:[1]
You can use the >
, child selector to refine the selectors to match only the <li>
elements immediately under <ul id="tab">
:
ul#tab > li {
display: none;
}
ul#tab > li.active {
display: block;
}
$("ul#tab > li:nth-child(" + nthChild + ")").addClass("active");
https://jsfiddle.net/63og0jue/
Without >
, the selectors will match any <li>
descendant of <ul id="tab">
:
<ul id="tab">
<li><!-- ... --></li>
<li>
<!-- ... -->
<li>one</li>
<li>Two</li>
<li>THree</li>
<!-- ... -->
</li>
<li><!-- ... --></li>
</ul>
ul#tab li:nth-child(1)
, for example, matches both of these as the first-child of their respective parents:
<li>one</li>
<li>
<p>HI There Enter personal Info</p>
</li>
Solution 2:[2]
The styles affecting the li's are defined as affecting all the li's inside the #tabs container. You can add the direct descendant selector (>) to the css styles fot the tabbed menu so that these styles don't affect other li's
ul#tabs {
list-style-type: none;
padding: 0;
text-align: center;
}
ul#tabs>li {
display: inline-block;
background-color: #32c896;
border-bottom: solid 5px #238b68;
padding: 5px 20px;
margin-bottom: 4px;
color: #fff;
cursor: pointer;
}
ul#tabs>li:hover {
background-color: #238b68;
}
ul#tabs>li.active {
background-color: #238b68;
}
ul#tab {
list-style-type: none;
margin: 0;
padding: 0;
}
ul#tab>li {
display: none;
}
ul#tab>li.active {
display: block;
}
Solution 3:[3]
In addition, there are methods that extract text and html from lists:
// takes out only child html code without ul-children
jQuery.fn.justlihtml = function() {
return $(this) .clone()
.children()
.remove("ul")
.end()
.html();
};
// takes out only text without tags
jQuery.fn.justtext = function() {
return $(this) .clone()
.children()
.remove("ul")
.end()
.text();
};
var litext = $(element).justtext();
var lihtml = $(element).justlihtml();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Juank |
Solution 3 | Mikeee |