Use property of an object when declaring it in javascript

0

Personal I'm starting in javascript and I have many questions related to objects. One of them is this: Let's suppose I create an object.

Here I have a list and I want to store it inside an object and a function of this object is used to change the color of this list.

(It's not exactly what I want to do but to understand)

var Objeto = { 
        //Aqui eu guardarei meu elemento.
		lista : document.getElementsByTagName('li'),
        //E esta funcao server para alterar o style das LIs.
		alt_cor : function(){
			Objeto.lista.setAttribute("style", "color:red");
				}
			}
			Objeto.alt_cor();
<ul class="lista_frutas">
  <li>Banana</li>
  <li>Laranja</li>
  <li>Maça</li>
</ul>
    
asked by anonymous 11.05.2017 / 15:51

2 answers

2

You have to change or take into account 2 things in your code for it to work:

  • Within this object the functions will run in the context of itself. This means that you can use this to access the Object.
  • .getElementsByTagName() gives you a list of elements. To use . setAttribute() you have to use an element, not a list of elements. So you have to iterate through those elements and use .setAttribute() one by one.

var Objeto = {
  lista: document.getElementsByTagName('li'),
  alt_cor: function() {
    for (var i = 0; i < this.lista.length; i++) {
      this.lista[i].setAttribute("style", "color: red;");
    }
  }
}
Objeto.alt_cor();
<ul class="lista_frutas">
  <li>Banana</li>
  <li>Laranja</li>
  <li>Maça</li>
</ul>
    
11.05.2017 / 16:52
1

Your code would look like below.

You create the object and it will decelerate your method inside it that receives as param paramenter which element wants to change.

Then out of the object you call the method and pass which list object you want to change color by its index.

There are a thousand ways to do this but I am giving a very simple and straightforward example for you to understand how a list and statement of methods works.

var objeto = {
	lista: document.getElementsByTagName('li'),
	alt_cor: function(elemento) {
		elemento.setAttribute("style", "color:red");
	}
};

objeto.alt_cor(objeto.lista[0]);
objeto.alt_cor(objeto.lista[1]);
objeto.alt_cor(objeto.lista[2]);
<ul class="lista_frutas">
  <li>Banana</li>
  <li>Laranja</li>
  <li>Maça</li>
</ul>
    
11.05.2017 / 16:09