Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

259
Visualizações
Unable to use value of variable inside nth-child selector in Javascript

I'm trying to use the value of a variable inside the element selector that is p:nth-child(0), instead of a number that is 0, I want to put the value of a variable, in this case, It is i of for loop.

But It is giving an error

        throw new Error("n-th rule couldn't be parsed ('" + formula + "')");
        ^

Error: n-th rule couldn't be parsed ('')

I don't know what the freak is happening here. As far as I can see, My code seems correct.

Here's my code -

const express = require("express");
const request = require("request");
const cheerio = require("cheerio");

const app = express();

app.get("/", function(req, res){

    var url = "randomGameDatabaseWebsite.com";


    // get content of url by request module
    request(url, function(err, response, html){
        if(!err && response.statusCode == 200){

            //load html to cheerio
            const $ = cheerio.load(html);

            //get game size
            var gameSizeP;
            var gameSizePStatus = false;
            
            for(var i = 0; gameSizePStatus == true; i++;){
                var text = $('p:nth-child('+i+')').text();

                if(text.includes("Size: ")){
                    gameSizePStatus = true;
                    gameSizeP = i;
                } else {
                    gameSizePStatus = false;
                }
            }

            const gameSize = $('p:nth-child('+gameSizeP+')').text();

            console.log(gameSize);
        }
    });
});

app.listen(3000, function(){
    console.log("Application is successfully started on port 3000");
})

Edit : For more proper understanding, What I'm trying to achieve here is to get the size of the game. It is listed on the website. But the Problem is the paragraph where the game size is written doesn't always stay the same. So What I'm doing here is trying to create is that check all paragraphs and find the paragraph which has text "Size: ".

In order to achieve this, I'm doing a for loop, which will loop through all paraphs and find game size's paragraph's nth-child number. So I created gameSizeP which will hold the paragraph number since we don't know the value, It is just initialized not declared. And I created an Boolen (gameSizePStatus) which is declared as false. So For Loop will continue it's loop until gameSizePStatus is true. and It will become true when It gets a Paragraph that contains text

And sorry for typo mistake I did on for loop's condition, I typed , instead of ;. And I'm stupid, I re-declared gameSizeP and gameSizePStatus. Fixed it but no changes to error. Getting same error.

And now when I try to run it, It throws an error. What is that error? wrote about it already above.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

IDK if it's the whole problem, but you are re-declaring the variables "gameSizePStatus" and "gameSizeP" in your loop. That's likely causing the "text" variable line to look for an element that doesn't exist at too high of a "i" value. This would also probably cause an error on your "gameSize" line for trying to find an empty string value. You should also do a null check before calling ".text()" so you don't throw an error when you reach an element that doesn't exist.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Rereading further, you have a comma in your for loop declaration instead of a semi-colon with an extra semi-colon after the "i++", and you aren't doing the loop anyway, since you assign "gameSizePStatus" to false and the loop wants it to be true. This means "gameSizeP" is empty when trying to run "$('p:nth-child('+gameSizeP+')')". Even if this doesn't error out, it would likely return undefined and throw an error on the ".text()".

Since I'm rewriting my comments as an answer, I'll also say that "gameSizePStatus" is an unnecessary variable. You can use other/better/simpler/cleaner logic to do the same thing. And you don't need to assign a value to "gameSizeP" when declaring it. This makes checking it's value easier later.

Here's my re-write of your code. I'm only including the relevant if statement for clarity.

if(!err && response.statusCode == 200){

    //load html to cheerio
    const $ = cheerio.load(html);

    //get game size
    var gameSizeP;
            
    for(var i = 0; ; i++){
        var text = $('p:nth-child('+i+')')?.text();

        if(text && text.includes("Size: ")){
            gameSizeP = i;
            break;
        }
    }

    if (!gameSizeP){
        return;
    }

    const gameSize = $('p:nth-child('+gameSizeP+')')?.text();
    
    if (gameSize) {
        console.log(gameSize);
        // and whatever else you need to do with gameSize
    }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda