Skip to content
Advertisement

How to get an element inside a function javascript

I’m trying to use the value that each book has on its “status” and make the function “changeStatus()” run but “book.status” is defined inside a function, how can I get it? or is there any other way i can change the button behavior on click? I tried using a querySelector but it only allows me to click one button per refresh

JavaScript
JavaScript
JavaScript

Advertisement

Answer

If you want to update the status of a book, you need a way to identify each book uniquely. Although it is possible to do this based on e.g. title or author, the reality is that those fields are not guaranteed to be unique.

Typically, you’d use the Id number of a database entry, but since you’re using mock data that isn’t realy an option here. We could e.g. use a UUID though:

JavaScript

Now we have a unique id, we can use it to couple each status button with a unique book entry. Lets adjust the HTML:

JavaScript

and lets write the update function:

JavaScript

And voila, we’re able to switch the status of any book!

I tried to stick as close to your code as possible so you’d better understand it, but a lot more improvements can be implemented, such as event listeners instead of explicitly calling the changeStatus function, but I’ll leave that as an exercise to you.

Full working example: codepen

Advertisement