Reputation: 1180
I have the following example code:
<ul class="name_of_class" id="TEST">
<li class="foo">1</li>
<li class="boo">2</li>
<li class="goo">3</li>
<ul>
When a specific <li>
is selected, the class changes to whatever the name is, plus sortUp
or sortDown
.
Example:
<ul class="name_of_class" id="TEST">
<li class="foo">111</li>
<li class="boo sortDown">222</li>
<li class="goo">333</li>
<ul>
I am trying to get the value of the actual text inside the <li>
, but I keep getting undefined.
var li = document.getElementById('TEST');
alert($('#TEST').filter('.sort').html());
I tried using different ways but no matter what I do I can't get the actual value, which in this case should be 222
.
Any idea what I am doing wrong?
Upvotes: 0
Views: 1127
Reputation: 31
Maybe you can try this:
alert($('#TEST').find('li[class^='sort']').html());
You will find a li element that has a class that starts with "sort". You can see more of this selector here.
Upvotes: 0
Reputation: 65883
I'm not sure what the classes have to do with your requirement to get the text of the clicked li
element. Just set up a click
event handler on the ul
and then in the handler, check the event target to ensure it was an li
, then just get the text of the event target.
document.getElementById("TEST").addEventListener("click", function(evt){
if(evt.target.nodeName==="LI"){
alert(evt.target.textContent);
}
});
<ul class="name_of_class" id="TEST">
<li class="foo">1</li>
<li class="boo">2</li>
<li class="goo">3</li>
<ul>
Upvotes: 1
Reputation: 17664
You can select the li
with either sortUp
or sortDown
by using the [attribute*="value"]
selector,
The [attribute*="value"] selector is used to select elements whose attribute value contains a specified value.
const li = document.querySelector('[class*="sort"]');
console.log(li.textContent);
li.style.background = "red";
<ul class="name_of_class" id="TEST">
<li class="foo">111</li>
<li class="boo sortDown">222</li>
<li class="goo">333</li>
<ul>
Upvotes: 1