Reputation: 261
So I have asked a question yesterday: Applying Accordion with div having data-attribute as title
But I found that this is not the desired method using data-attr as I cannot use it as a selector in jQuery when I want to make a toggle with it.
I got a structure like this... to display the title before the div.
li {
list-style: none;
}
div {
background: lightgray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li id="first">1st Title</li>
<li id="second">2nd Title</li>
<li id="third">3rd Title</li>
<li id="fourth">4th Title</li>
</ul>
<div id="first_div">First content <br/>1111111111111111111111</div>
<div id="second_div">Second content <br/>22222222222222222222</div>
<div id="third_div">Third content <br/>33333333333333333333</div>
<div id="fourth_div">Fourth content <br/>4444444444444444444</div>
I want to make it like
1st Title
2nd Title
3rd Title
4th Title
-> Click "1st Title", it becomes
1st Title
First Content
2nd Title
3rd Title
4th Title
And similar when clicking the other titles Without changing the html structure (ul li come first and div after)
Can anyone provide me some solution as I have already struggling with this one for days... would like to know how to solve it! Thanks!
Upvotes: 0
Views: 707
Reputation: 608
Is this what you want to achieve?
$("li").on("click", function(e) {
$("li").not(this).removeClass("has-content");
$("li").not(this).find(".extra").remove();
// console.log("ID", $(this).attr("id"));
var div_id = "#" + $(this).attr("id") + "_div";
var div_content = $(div_id).html();
// console.log(div_content);
if (!$(this).hasClass("has-content")) {
$(this)
.addClass("has-content")
.append("<div class='extra'>" + div_content + "</div>");
}
else {
$(this).removeClass("has-content");
$(this).find(".extra").remove();
}
});
ul {
margin: 0;
padding: 0;
}
li {
list-style: none;
padding: 10px 0;
background: #ff0;
}
div {
background: lightgray;
display: none;
}
div.extra {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li id="first">1st Title</li>
<li id="second">2nd Title</li>
<li id="third">3rd Title</li>
<li id="fourth">4th Title</li>
</ul>
<div id="first_div">First content <br/>1111111111111111111111</div>
<div id="second_div">Second content <br/>22222222222222222222</div>
<div id="third_div">Third content <br/>33333333333333333333</div>
<div id="fourth_div">Fourth content <br/>4444444444444444444</div>
Upvotes: 1