skip to Main Content

I wanted to add ‘selected’ attribute by comparing the value between <li></li>

<ul class="list">
<li data-value="0" class="option" selected>All Categories</li>
<li data-value="75" class="option">eBriefs</li>
<li data-value="74" class="option">Hawkeye-articles</li>
<li data-value="1" class="option">Hhhhh</li>
<li data-value="93" class="option focus">Hyphen-Newsletter</li>
<li data-value="95" class="option">Infographics</li>
<li data-value="76" class="option">News</li>
<li data-value="134" class="option">Podcast-webinar</li>
<li data-value="79" class="option">Podcasts</li>
<li data-value="81" class="option">Success Stories</li>
<li data-value="94" class="option">Videos</li>
<li data-value="77" class="option">Webinars</li>
<li data-value="83" class="option">Whitepapers</li>
</ul>

For example, I wanted to add ‘selected’ attribute to Podcasts, and removing selected from All Categories option.

Like, I wanted to check if the text between <li></li> is Podcasts then put selected attribute in <li data-value="79" class="option">Podcasts</li>

and make it

<li data-value="79" class="option" selected>Podcasts</li>

Major goal is to put selected attribute by comparing value <li></li>

How can I do it with jQuery or javascript?

5

Answers


  1. You can use element.childNodes to get all children. Then iterate over them and remove the attribute selected with element.removeAttribute.

    You can use element.textContent to get the content of the <li> element. If it fits your search you can then use element.setAttribute() to mark it as selected.

    I prepared a small example of this here: https://jsfiddle.net/xLfp8z57/1/

    <ul class="list">
      <li data-value="0" class="option" selected>All Categories</li>
      <li data-value="75" class="option">eBriefs</li>
      <li data-value="74" class="option">Hawkeye-articles</li>
      <li data-value="1" class="option">Hhhhh</li>
      <li data-value="93" class="option focus">Hyphen-Newsletter</li>
      <li data-value="95" class="option">Infographics</li>
      <li data-value="76" class="option">News</li>
      <li data-value="134" class="option">Podcast-webinar</li>
      <li data-value="79" class="option">Podcasts</li>
      <li data-value="81" class="option">Success Stories</li>
      <li data-value="94" class="option">Videos</li>
      <li data-value="77" class="option">Webinars</li>
      <li data-value="83" class="option">Whitepapers</li>
    </ul>
    
    <button id="btn">unselect all</button>
    
    <button id="btn2">select all ending with 'r'</button>
    
    document.getElementById("btn").addEventListener("click", event => unselectAll());
    document.getElementById("btn2").addEventListener("click", event => selectSpecific());
    
    function unselectAll() {
      let list = document.querySelector(".list")
    
      list.childNodes.forEach(item => {
        if (item.tagName === 'LI') {
          item.removeAttribute("selected")
        }
      });
    }
    
    function selectSpecific() {
      let list = document.querySelector(".list")
    
      list.childNodes.forEach(item => {
        if (item.tagName === 'LI' && item.textContent.endsWith("r")) {
          item.setAttribute("selected", "");
        }
      });
    }
    
    li[selected]{
      color: red;
    }
    
    Login or Signup to reply.
  2. selected isn’t a permissible attribute on a list item so I suggest making selected another class, and then using a function to toggle that class on/off.

    // Cache the list items, and coerce them to an array
    // so we can use array methods on it
    const list = [...document.querySelectorAll('.option')];
    
    // Accepts a list, and a string of text
    function toggleSelect(list, text) {
    
      // `find` the list item that has textContent matching
      // the text argument
      const found = list.find(li => li.textContent === text);
    
      // And if it finds it, toggle its class
      if (found) found.classList.toggle('selected');
    }
    
    // Using a timeout here so you can see
    // the result more clearly
    setTimeout(() => {
      toggleSelect(list, 'All Categories');
      toggleSelect(list, 'Podcasts');
    }, 2000);
    .selected { color: red; }
    <ul class="list">
      <li data-value="0" class="option selected">All Categories</li>
      <li data-value="75" class="option">eBriefs</li>
      <li data-value="74" class="option">Hawkeye-articles</li>
      <li data-value="1" class="option">Hhhhh</li>
      <li data-value="93" class="option focus">Hyphen-Newsletter</li>
      <li data-value="95" class="option">Infographics</li>
      <li data-value="76" class="option">News</li>
      <li data-value="134" class="option">Podcast-webinar</li>
      <li data-value="79" class="option">Podcasts</li>
      <li data-value="81" class="option">Success Stories</li>
      <li data-value="94" class="option">Videos</li>
      <li data-value="77" class="option">Webinars</li>
      <li data-value="83" class="option">Whitepapers</li>
    </ul>
    Login or Signup to reply.
  3. Jquery and Vanilla js examples to demonstrate what you want. Also there are other solutions resembling this solution as you can see on other answers.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <ul class="list">
        <li data-value="0" class="option" selected>All Categories</li>
        <li data-value="75" class="option">eBriefs</li>
        <li data-value="74" class="option">Hawkeye-articles</li>
        <li data-value="1" class="option">Hhhhh</li>
        <li data-value="93" class="option focus">Hyphen-Newsletter</li>
        <li data-value="95" class="option">Infographics</li>
        <li data-value="76" class="option">News</li>
        <li data-value="134" class="option">Podcast-webinar</li>
        <li data-value="79" class="option">Podcasts</li>
        <li data-value="81" class="option">Success Stories</li>
        <li data-value="94" class="option">Videos</li>
        <li data-value="77" class="option">Webinars</li>
        <li data-value="83" class="option">Whitepapers</li>
    </ul>
    <script>
        //Vanilla js
        document.querySelectorAll('.option').forEach(elem => {
            if (elem.innerHTML == 'Podcasts')
            elem.setAttribute('selected', '')
            else
            elem.removeAttribute('selected')
        })
        //Jquery
        const selectIt = $('.option:contains("Podcasts")')
        if (selectIt)
            selectIt.attr('selected', '')
        else
            selectIt.removeAttr('selected')
    </script>
    Login or Signup to reply.
  4. document.getElementsByClassName("list")[0].children[0].removeAttribute("selected")

    document.getElementsByClassName("list")[0].children[1].setAttribute("selected", '')

    children[0] is the first element
    children[1] is the second and so on

    Login or Signup to reply.
  5. Using jquery, .removeAttr() will remove an existing attribute and .attr("name", "") will add a flag attribute:

    You can use $("[attribute]") to select elements with a specific attribute, giving a succinct:

    $("[selected]").removeAttr("selected");
    $(".list .option").filter((i, e) => $(e).text() == "Podcasts").attr("selected", "")
    

    Updated snippet:

    $("[selected]").removeAttr("selected");
    $(".list .option").filter((i, e) => $(e).text() == "Podcasts").attr("selected", "")
    [selected] { background-color: pink; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul class="list">
      <li data-value="0" class="option" selected>All Categories</li>
      <li data-value="75" class="option">eBriefs</li>
      <li data-value="74" class="option">Hawkeye-articles</li>
      <li data-value="1" class="option">Hhhhh</li>
      <li data-value="93" class="option focus">Hyphen-Newsletter</li>
      <li data-value="95" class="option">Infographics</li>
      <li data-value="76" class="option">News</li>
      <li data-value="134" class="option">Podcast-webinar</li>
      <li data-value="79" class="option">Podcasts</li>
      <li data-value="81" class="option">Success Stories</li>
      <li data-value="94" class="option">Videos</li>
      <li data-value="77" class="option">Webinars</li>
      <li data-value="83" class="option">Whitepapers</li>
    </ul>

    As noted elsewhere, selected should ideally not be added as an attribute to a li. Using a class should have the same affect, though there may be some other reason for using an attribute not mentioned in the question.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search