Home > Enterprise >  how to add 'selected' attribute in <li> using jQuery or Javascript
how to add 'selected' attribute in <li> using jQuery or Javascript

Time:08-18

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

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

and make it

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

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

How can I do it with jQuery or javascript?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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 >
    <li data-value="0"  selected>All Categories</li>
    <li data-value="75" >eBriefs</li>
    <li data-value="74" >Hawkeye-articles</li>
    <li data-value="1" >Hhhhh</li>
    <li data-value="93" >Hyphen-Newsletter</li>
    <li data-value="95" >Infographics</li>
    <li data-value="76" >News</li>
    <li data-value="134" >Podcast-webinar</li>
    <li data-value="79" >Podcasts</li>
    <li data-value="81" >Success Stories</li>
    <li data-value="94" >Videos</li>
    <li data-value="77" >Webinars</li>
    <li data-value="83" >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>

CodePudding user response:

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 >
  <li data-value="0"  selected>All Categories</li>
  <li data-value="75" >eBriefs</li>
  <li data-value="74" >Hawkeye-articles</li>
  <li data-value="1" >Hhhhh</li>
  <li data-value="93" >Hyphen-Newsletter</li>
  <li data-value="95" >Infographics</li>
  <li data-value="76" >News</li>
  <li data-value="134" >Podcast-webinar</li>
  <li data-value="79" >Podcasts</li>
  <li data-value="81" >Success Stories</li>
  <li data-value="94" >Videos</li>
  <li data-value="77" >Webinars</li>
  <li data-value="83" >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.

CodePudding user response:

You can use element.childNodes to get all children. Then itterate 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 >
  <li data-value="0"  selected>All Categories</li>
  <li data-value="75" >eBriefs</li>
  <li data-value="74" >Hawkeye-articles</li>
  <li data-value="1" >Hhhhh</li>
  <li data-value="93" >Hyphen-Newsletter</li>
  <li data-value="95" >Infographics</li>
  <li data-value="76" >News</li>
  <li data-value="134" >Podcast-webinar</li>
  <li data-value="79" >Podcasts</li>
  <li data-value="81" >Success Stories</li>
  <li data-value="94" >Videos</li>
  <li data-value="77" >Webinars</li>
  <li data-value="83" >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;
}
  • Related