Home > Blockchain >  How can I loop through a string array and only get the value of the data attribute that is clicked o
How can I loop through a string array and only get the value of the data attribute that is clicked o

Time:03-09

I am trying to get from the <ul > to the tester class where I want to loop over the children that has data-section and only show it if it matches up with the <ul >

See the screenshot of the HTML from Google Dev tools - https://ibb.co/Y3g1jmC

my code to show this is below:

$(".click-to-section li").click(function() {
    $(this).each(function(){
    let testdata = $(this).data('section');
                            
   let testdata2 = $(this).closest("main").next().next().children();
   $(testdata2).each(function(){
       const dataSection = $(this).data("section");
       console.log(dataSection);
   });
 });  
});

HTML

<ul >
        <li data-section="videos">Videos</li> **When this is clicked**
        <li data-section="lo">Learning objectives</li>
        <li data-section="credits">Credit</li>
        <li data-section="toolkits">Toolkit</li>
    </ul>

<div ></div>
<div > **Needs to traverse to this div and loop through the children to show the sections one at a time based on the data-section in the ul menu to equal the data-section here **
    <div data-section="credits"  style="display: none;"</div>
    <section data-section="videos" ></section>
    <div  data-section="lo" style="display: none;"></div>
    <div data-section="toolkits"  style="display: none;"></div>
</div>

CodePudding user response:

Updated the code to click on li and show tester elements that matches data attributes of clicked li

Working Code below

$(".click-to-section li").on("click", function() {
  var dataSection = $(this).attr("data-section");
  $(".tester > *").hide();
  $(".tester [data-section="   dataSection   "]").show();
})
li {
  cursor: pointer
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul >
  <li data-section="videos">Videos</li> **When this is clicked**
  <li data-section="lo">Learning objectives</li>
  <li data-section="credits">Credit</li>
  <li data-section="toolkits">Toolkit</li>
</ul>

<div ></div>
<div >
  <div data-section="credits" >cred </div>
  <section data-section="videos" >video</section>
  <div  data-section="lo">lo</div>
  <div data-section="toolkits" >js tabs</div>
</div>

  • Related