简体   繁体   中英

Parsing horribly deprecated HTML with jQuery

I'm having some trouble understanding how to use nested selectors in jQuery. I'm parsing a list of classes from my university and I want it to let me know if a class I want is open. However, the website doesn't use css AT ALL, so the only way of identifying the class I want is open is to read the color attribute of the font tag.

Here's the block of HTML I'm trying to read

<TD><FONT FACE='Arial' SIZE='-1' COLOR='Black'>nameOfClass</TD>

Here's how am I'm trying to read it, and display an alert if the font tag attribute color of nameOfClass is "Black", which means its open. It's nasty but its the only way I can tell if the class is available or not.

    function main() {

    $(document).ready(function(){
        if $("td").text()=="nameOfClass" 
            if $(this "font").attr("COLOR")=="Black" {
                alert("It actually works!");
            }
        });

I never get an alert when I run this though. I'm pretty sure its my syntax, it's been a long while since I did any sort of coding so I might be making some stupid mistake.

You can use .children . But in order for your code to work, you have to iterate over all td elements, not just compare the text value of the first one:

$("td").each(function() {
    if($(this).text() === 'nameOfClass' && 
       $(this).children('font').attr('color') === 'Black') {
           alert("It actually works!");
    }
});

Otherwise, $("td").text()=="nameOfClass" only tests whether the text of the first td element in the page is "nameOfClass", which is certainly not what you want. You want to find all td element which contain that string.


You could do it much simpler if you'd directly select all font elements whose color attribute has the value "Black", with the attribute selector . Then you filter out the ones that don't contain the class name and count how many elements are left over. If none, then the class is not open.

var classIsOpen = $('font[color="Black"]').filter(function() { 
   return $(this).text() === 'nameOfClass';
}).length > 0;

You only need to do an exact comparison of the class name if it could occur as part of an other name, eg "Web" and "Advanced Web". If that's not the case, you can make the code even shorter, with the :contains selector:

var classIsOpen = $('font[color="Black"]:contains("nameOfClass")').length > 0;

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