0

I'm working on an online quiz app. The quizes are divided in terms of chapters such that each chapter has its own quiz. Each chapter is attached to a menu and onclick on a menu, a chapter is loaded with some content and at the end there's a button to start a quiz.

As the user takes the quiz, there's a button to navigate to the next question. on finishing the last question, the score for the quiz will be displayed alongside a button to click to be navigated to the next chapter. all this is to be done dynamically. what i want is, on this button that will navigate to the next chapter, i pass the id of the next chapter in this button

This is the jquery bit that is handling the last part i've described above(the click event handles submission of a question):

$(document).ready(function(){
     $("#page-content-wrapper").on('click', '.questionform #submit', function(e)  
     {
          //more code before this
          var next_chapter = $("a[data-menu='" + next_menu +"']")[0];
          console.log(next_chapter);
     });
});

the variable next_chapter holds the entire html link for the next menu. i.e.

console.log(next_chapter);

returns:

<a href="#signs-giving-orders" id="2" data-menu="2">Signs Giving Orders</a>

now what i want is to capture the id and pass it the button value. i've tried getting the id using both the .find and .attr methods as such:

var next_chapter = $("a[data-menu='" + next_menu +"']")[0].attr('id');
var next_chapter = $("a[data-menu='" + next_menu +"']")[0].find('a').attr('id');

but both the above throw an error: Uncaught TypeError: $(...)[0].attr is not a function and Uncaught TypeError: $(...)[0].find is not a function respectively.

So in short, how do i retrieve the id of this dynamic result: <a href="#signs-giving-orders" id="2" data-menu="2">Signs Giving Orders</a>

2 Answers 2

2

You don't need to use [0], it returns the reference to native DOM element thus you were getting the error.

As you want to get the attribute value, directly use .attr() on jQuery object

var next_chapter = $("a[data-menu='" + next_menu +"']").attr('id');
                                                      //Notice [0] is removed
Sign up to request clarification or add additional context in comments.

Comments

1

Yes, because .attr() method of jQuery element, not native one

So do this

var next_chapter = $("a[data-menu='" + next_menu +"']")[0].id;

One more option

var next_chapter = $("a[data-menu='" + next_menu +"']")[0].getAttribute('id');

Also you can check https://www.w3schools.com/jsref/met_element_getattribute.asp

And https://developer.mozilla.org/en/docs/Web/API/Element/attributes

Comments

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.