Home > Mobile >  How to get values from <li> elements?
How to get values from <li> elements?

Time:10-28

I have three different sections for filter and a button and i want to use filter on these sections, I just want to know that how can i get value of these sections ( inside ul li)

<div id="new-items" >
<a href="#" >New Items</a>
<ul >
  <li><span>New bestsellers</span></li>
  <li><span>New releases</span></li>
</ul>
</div>
<div id="buy" >
  <a href="#" >Buy Now</a>
  <ul >
    <li><span>Wallet</span></li>
    <li><span>Website</span></li>
  </ul>
</div>
<div id="sort-by" >
  <a href="#" >Sort By</a>
  <ul >
    <li><span>Low To High Price</span></li>
    <li><span>High To Low Price</span></li>
    <li><span>View</span></li>
    <li><span>View</span></li>
    <li><span>Rating</span></li>
    <li><span>Sale</span></li>
    <li><span>Date</span></li>
  </ul>
</div>

<button ><span>Filter</span> </button>

CodePudding user response:

This is how your HTML now renders

enter image description here

You need to convert the <li> to radio buttons.
For example, the sort choices.

<input type="radio" name="sort" value="1"> Low To High Price<br>
<input type="radio" name="sort" value="2"> High To Low Price<br>
<input type="radio" name="sort" value="3"> View<br>
<input type="radio" name="sort" value="4"> View<br>
<input type="radio" name="sort" value="5"> Rating<br>
<input type="radio" name="sort" value="6"> Sale<br>
<input type="radio" name="sort" value="7"> Date<br>

The above looks like this:

enter image description here

CodePudding user response:

It may not be jQuery but it is simple enough in vanilla Javascript. The comments tell you what is happening.

// a global variable to be populated when specific SPAN elements are clicked.
let selection=false;

// bind a delegated listener to the document or suitable ancestor
document.addEventListener('click',e=>{
  // If the "click" is on a SPAN of interest, populate the global variable
  if( e.target.tagName=='SPAN' && e.target.parentNode.tagName=='LI' ){
    selection=e.target;
  }
  // if the button is clicked, filter ...
  if( e.target.tagName=='SPAN' && e.target.parentNode.tagName=='BUTTON' && selection ){
    alert(selection.textContent)
  }
});
<div id="new-items" >
  <a href="#" >New Items</a>
  <ul >
    <li><span>New bestsellers</span></li>
    <li><span>New releases</span></li>
  </ul>
</div>

<div id="buy" >
  <a href="#" >Buy Now</a>
  <ul >
    <li><span>Wallet</span></li>
    <li><span>Website</span></li>
  </ul>
</div>

<div id="sort-by" >
  <a href="#" >Sort By</a>
  <ul >
    <li><span>Low To High Price</span></li>
    <li><span>High To Low Price</span></li>
    <li><span>View</span></li>
    <li><span>View</span></li>
    <li><span>Rating</span></li>
    <li><span>Sale</span></li>
    <li><span>Date</span></li>
  </ul>
</div>

<button ><span>Filter</span></button>

  • Related