0

How can I get the index, document.getElementsByClassName("selected")[i].css("background-color", "green"); is not working

$(function(){
    $("#but").click(function () {
        var corr = $(".lblcorrectans");
        var selected = $(".selected");

        for (var i = 0; i < model.length; i++) {
            if (corr[i].innerHTML == selected[i].innerHTML) {
                document.getElementsByClassName("selected")[i].css("background-color", "green");
            }
            else {
                document.getElementsByClassName("selected")[i].css("background-color", "red");
            }
        }
    });
});
6
  • what is model, eg model.length? Commented Jul 21, 2020 at 11:34
  • that means that item does not exist Commented Jul 21, 2020 at 11:38
  • This looks way too complicated. Can you include all the relevant code and markup? Commented Jul 21, 2020 at 11:50
  • @Elvin You can accept my answer if it solved your problem Commented Jul 21, 2020 at 12:11
  • @Argee sorry ..i forgot write this [model = @Html.Raw(Json.Encode(Model))] .... Commented Jul 21, 2020 at 18:22

2 Answers 2

1

The getElementsByClassName will return a list of Html Collection and you can access a specific element via index if it exists in the Collection.

[NOTE] However, you are using css function of the jQuery with Html Element which actually does not exist. Here's how you should do that with Jquery. You basically need to use the EQ API of the Jquery

$('.para').eq(0).css({'background-color': 'red'}) // eq(i) or whatever the index is
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="para">First Para</p>
<p class="para">Second Para</p>

Sign up to request clarification or add additional context in comments.

Comments

0

Why not just iterate with forEach?

Array.from(document.getElementsByClassName('selected')).forEach(e => {
  e.style.backgroundColor = 'red';
});

1 Comment

OP is already using jQuery. Why so complicated? What is HTMLElement#css()?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.