Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if selectors are blank in jQuery

I am currently using a .js file with jQuery commands to find certain elements of a .xml file. I have been able to gather all the data I want easily, however am having a bit of difficulty with the presentation.

I am using the same .js script for the loading of multiple .xml files. The data is gathered in an html document and in list form. Here is the code:

        $upgrade1 = $(xml).find("upgrades").eq(0).next();
        $upgrade2 = $(xml).find("upgrades").eq(1).next();
        $upgrade3 = $(xml).find("upgrades").eq(2).next();
        $("#upgrades").append($upgrade1.text() + "<li>" + $upgrade2.text() + "</li><li>" + $upgrade3.text() + "</li>");

Now as you can see first the selectors compile the text they need and then it is added to the <li class ="upgrades">. Now the issue here is that some .xml files will only have 1 or 2 upgrades rather than all 3. Yet the function will still draw out blank bullet points due to the <li> elements in the .append()

The easiest solution is the use an if statement, however I can't seem to find anywhere how you would check if the selector is blank? There are only mentions of checking form elements, but this is not helpful to me. Possibly a way to check for an empty string or a string of less than 1 character? I don't know...

Does anyone have any ideas?

like image 717
user2242999 Avatar asked Dec 27 '22 06:12

user2242999


2 Answers

Use length.

if ($('whatever').length == 0) {
  // It's empty
}
like image 74
meagar Avatar answered Jan 13 '23 08:01

meagar


You can also use your selector implicitly by invoking an each on your query.

$("whatever").each(function () {
    var ctl = $(this);
    ctl.text("bob jones");
});

In this way you're automatically casting off instances where you don't get any results back.

like image 31
Thomas Ingham Avatar answered Jan 13 '23 08:01

Thomas Ingham