Home > front end >  querySelector or getElementById not working
querySelector or getElementById not working

Time:09-11

So i am in the process of making a web app (experimental) that has a quiz in it. I am using a python file for questions and the function for the quiz. The problem is with the javascript, it is not selecting the tags that i want. Here's the code

{% extends "layout.html" %}

{% block title %}
    Quiz Begin
{% endblock %}

{% block body %}

{% for q in qna %}
<div>
    <h3>{{ q["question"] }} </h3>
    <input  type="text">
    <p  style="display:none;">{{ q["answer"] }}</p>
</div>
{% endfor %}

<footer>
    <button id="check">Check Answer</button>
</footer>

<script>

    // correct this or start from scratch because this is not working

    var qna = {{ qna | tojson }};
    var right = 0;
    var wrong = 0;

    document.querySelector("#check").addEventListener('click', function() {
        var id, tmp, input, answer;
        for (let q = parseInt("{{ qna[0]['id'] }}"); q <= parseInt("{{ qna|length }}"); q  ) {
            id = q.toString();
            tmp = document.getElementsByClassName(id);
            input = tmp.querySelector('input').value.toUpperCase();
            answer = tmp.getElementByTagName('p').value.toUpperCase();
            if (parseInt(input) == parseInt(answer)) {
                right  ;
            }
            else {
                wrong  ;
            }
        }
    });
</script>

{% endblock %}

The python codes are

def quiz_begin():
return render_template("begin.html", qna=questions())

And

def questions():
return [{"id": 1,
        "question": "2   2 = ?",
        "answer": 4},
        {"id": 2,
        "question": "68 x 45 = ?",
        "answer": 3060},]

The problem lies after the tmp variable is declared in the script. the tmp.querySelector doesn't seem to work and return the tag. It just stops there. I have tried some different functions like getElementByTagName but they dont seem to work either. if there is any other way then please help. Thanks for helping in advance.

CodePudding user response:

getElementsByClassName returns a HTMLCollection (iterator of node elements), so you should loop througt them, oder take a single one, like:

tmps = document.getElementsByClassName(id);
for(let j = 0; j < tmps.length, j  ) {
    input = tmps[j].querySelector('input').value.toUpperCase();
}

or

tmps = document.getElementsByClassName(id);
if (tmps.length)
    input = tmps[0].querySelector('input').value.toUpperCase();
}

CodePudding user response:

document.querySelector uses the CSS selector syntax to find elements. Did you try this?

tmp = document.querySelector('.'   id);

For querying by class names e.g. "foo" you can use document.querySelector('.foo').

But be aware that document.querySelector will return you only the first element found in the DOM. Whereas document.querySelectorAll would return you also an HTMLCollection.

  • Related