How to change an attribute, javascript

Asked

Viewed 213 times

3

I’m trying to change the value of an attribute but apparently nothing changes, see the example used:

console.log(document.getElementById("stars").offsetTop); // me retorna 83
document.getElementById("stars").offsetTop = 10;
console.log(document.getElementById("stars").offsetTop); // continua retornando 83

1 answer

1


Your method used as an example is the problem, the offsetTop is a method get, and not set. That is, with it you can only get values and not declare them or change them. In the case as the offsetTop capture the top of the element in question (in pixels), the most you can do to change it is through css:

document.getElementById("stars").style.top = valor
// O propriedade top só pode ser usada após a declaraçã o da propriedade position...

But you can change the "attributes" by javascript, for example with the method scrollTop. Look at this example:

 console.log(document.getElementById("stars").scrollTop); // retornará 0
 document.getElementById("stars").scrollTop = 10;
 console.log(document.getElementById("stars").scrollTop); // retornará 10

The method scrollTop yes is a method get/set. With it you capture and determine values.

Demonstration - Jsfiddle

  • Thanks for explaining, I didn’t know you had this one because..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.