MOD ER HACKS
MOD ER HACKS

Reputation: 197

How to add custom properties to custom constructors in javascript?

I want to make a custom javascript constructor with custom properties. Lets imagine of how it may look like :

 var a = new MyCustomConstructor({
  selector: ".demo",
  html: "Hello World !",
  style: {
     color : "white",
     background : "blue"
  }
 });

The above example adds the text Hello World ! to all the elements with class demo with given styles. How can I make this happen actually ? I will like to achieve it with ES5 but also ES6 where necessary but no library. Can I do it ? If yes then how ?

Thanks in advance.

Upvotes: 1

Views: 345

Answers (2)

debarchito
debarchito

Reputation: 1335

I have a quite good solution to that. So, here is a piece of code :

 function MyCustomConstructor(stock) {
   var sel = document.querySelectorAll(stock.selector); // Selecting all matching elements in your selector method
   for( var i = 0; i < sel.length; ++i ) {
     sel[i].innerHTML += stock.html; // Setting the text 
     sel[i].style.cssText = stock.style; // Setting css properties with values
     sel[i].style[stock.css.prop] = stock.css.val; // You can also nest them
   };
 };

You can use it as :

 var a = new MyCustomConstructor({
   selector: ".demo",
   html: "Hello World !",
   style: "background : blue",
   css: {
      prop: "color",
      val: "white",
   }
  });

Upvotes: 1

dganenco
dganenco

Reputation: 1616

The above example adds the text Hello World ! to all the elements with class demo. How can I make this happen actually

Answering your question you can simply find all elements with class=demo and set their text:

const elements = document.getElementsByClassName('demo');
for (let el of elements) {
  el.innerText = 'Hello World!'
}
<span class='demo'>

</span>

<span class='demo'>

</span>

<span class='demo'>

</span>

Also I'd advise you to read about js constructors this good article.

Upvotes: 0

Related Questions