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
You can use
element.childNodes
to get all children. Then iterate over them and remove the attribute selected withelement.removeAttribute
.You can use
element.textContent
to get the content of the<li>
element. If it fits your search you can then useelement.setAttribute()
to mark it as selected.I prepared a small example of this here: https://jsfiddle.net/xLfp8z57/1/
selected
isn’t a permissible attribute on a list item so I suggest makingselected
another class, and then using a function to toggle that class on/off.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.
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
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:Updated snippet:
As noted elsewhere,
selected
should ideally not be added as an attribute to ali
. Using a class should have the same affect, though there may be some other reason for using an attribute not mentioned in the question.