Try to search your question here, if you can't find : Ask Any Question Now ?

How to pass a single element to a Class constructor when I have a group of elements on a page?

HomeCategory: stackoverflowHow to pass a single element to a Class constructor when I have a group of elements on a page?
Avatarkundan asked 2 weeks ago

I’ve been doing the research on Slack and elsewhere, but I am not able to find an answer to my question. I feel I lack some basic knowledge of OOP, which probably will take me hours of researching and coding before I get to the answer. But somehow I am perplexed that it might be such a complex issue.

The question is:
I have two buttons with the same class on a page (this is just for example). I create JS to handle the behaviour via Class function. In constructor I define an element I want the Class to point to, namely child. However, I want the Class to point to one of two child separately when clicking on them. However, this.child in constructor always points to two child elements.

Can you please help and tell what I am doing wrong?

const selectors = {
	childElement: '.child'
},
$ = jQuery;

class Child {
  constructor() {
    this.child = $(selectors.childElement);
    this.bindUiEvents();
  }
  
  bindUiEvents() {
  	$(this.child).on('click', this.addStyles);
  }
  
  addStyles() {
  	$(this).addClass('coloured');
  }
}

new Child();
.child {
  height: 100px;
  width: 100px;
  border: 1px solid black;
}

.child.coloured {
  background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
<button class="child">First</button>
<button class="child">Second</button>
</div>
1 Answers
Best Answer
AvatarJyoti answered 2 weeks ago
Your Answer

2 + 15 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com