1

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.

0

2 Answers 2

1

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",
   }
  });
Sign up to request clarification or add additional context in comments.

Comments

0

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.

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.