Joey Hipolito
Joey Hipolito

Reputation: 3166

Equivalent of $(this) in native javascript

I wanted to add and event listener to a button and I am still relatively new on coding purely on javascript, so I don't know what are the native equivalent of $this

in my code

// the markup

<ul class="menu">
   <li><a href="#" data-something="value">text</a></li>
   <li><a href="#" data-something="value2">text2</a></li>
</ul>

var menu = document.querySelector(".menu");
menu.addEventListener("click", function(){
    // console.log $(this).val
    // what I wanted is to get that data-attribute of the clicked item
});

Upvotes: 6

Views: 12610

Answers (2)

Gibin Ealias
Gibin Ealias

Reputation: 2859

You could use the below code to get an almost equivalent of $(this)

document.querySelector("#myId").addEventListener("click", function(e) {
  console.log(this);    //Prints the Element
  $this = new Array(e.target);
  console.log($this);   //Prints the Object
});

PEN

Hope this helps.

Upvotes: 1

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

Within the event handler this will represent the element to which the event handler is bound. You will not have all of the utility functions provided by jQuery. So in your example you will not be able to retrieve the data attribute by using this.data("something")

To retrieve the value of the custom attribute the code must pass the event to the function. From the event or e in the example, the target property will contain the element that triggered the event, which may not always be the element to which the event handler was bound, due to the propagation of events. Use the getAttribute method to retrieve the value of custom attribute. Also refrain from making the custom attributes upper case as the html specifications do not allow for this and will create inaccessible attributes.

var menu = document.querySelector(".menu");
menu.addEventListener("click", function(e){
    alert(e.target.getAttribute("data-something"));
});

JS Fiddle: http://jsfiddle.net/pjcvB/

Upvotes: 7

Related Questions