简体   繁体   中英

Select sub element based on classes it has

Below is the HTML that I have

<ul id="QBS">
  <li>
    <a class="qb_mode starting Rodgers" href="#">See Stats</a>
  </li>
  <li>
    <a class="qb_mode Manning" href="#">See Stats</a>
  </li>
  <li>
    <a class="qb_mode Brady" href="#">See Stats</a>
  </li>
</ul>

I want to find this unordered list, then tell which item has the starting qb class and then return the class that has their name (brady rodger manning) etc.

What's throwing me in a loop is the fact that the link is wrapped in the list element.

Here is what I am trying:

element = $("#qbs"); // pretty sure I want this vs getElementbyDocumentID
children = element.children();` // gets me all the list elements

for (i=0;i<children.length;i++) {
  grandchild = children[i].children();
  ???? How would I get the 3rd class on this element?
}

Sorry about the formatting.

How about this?

var allClasses = $("#QBS").find('li a[class^="qb_"]')
     .map(function () { 
          return this.className.split(" ").pop();
}).get();
console.log(allClasses);

Fiddle

Provided the class started with qb_* is at the beginning and you want to take only the last class of the match.

if all your class names are qb_mode then:

var allClasses = $("#QBS").find('.qb_mode').map(function () {
    return this.className.split(" ").pop();
}).get();

if you want all of them then:

var allClasses = $("#QBS").find('.qb_mode').map(function () {
    var cls = this.className.replace(/qb_mode/,'');
    return cls.trim().split(/\W+/);
}).get();
console.log(allClasses);

Fiddle

If I understood you correctly, how about:

var name = $('#QBS a.qb_mode.starting').prop('class').replace(/\s*(qb_mode|starting)\s*/g,'');
console.log(name); // Rogers

See demo here .

a=document.getElementById('QBS');
var b=a.getElementsByClassName("qb_mode");
var i, j=b.length, result=[];
for(i=0;i<j;i++) {
  c=b[i].className.split(" ");
  result.push(c.pop());
}
return result;

fiddle http://jsfiddle.net/3Amt3/

var names=[];

$("#QBS > li a").each(function(i){
    var a=$(this).attr("class").split(" ");
    names[i]=a[(a.length-1)];
    console.log("Name  is " + names[i]);    
 });

or a more precise selector

 $("#QBS > li a.qb_mode").each( ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM