Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
});
like image 496
Joey Hipolito Avatar asked Sep 02 '13 18:09

Joey Hipolito


People also ask

What is $( this in JavaScript?

$(this) is a jQuery object and this is a pure DOM Element object. See this example: $(".test"). click(function(){ alert($(this). text()); //and alert(this.

What can replace jQuery () in a function call?

The equivalent to $() or jQuery() in JavaScript is querySelector() or querySelectorAll() , which, just like with jQuery, you can call with a CSS selector.

Is querySelector jQuery?

querySelector() and querySelectorAll() are two jQuery functions which helps the HTML elements to be passed as a parameter by using CSS selectors ('id', 'class') can be selected.


2 Answers

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/

like image 181
Kevin Bowersox Avatar answered Sep 29 '22 17:09

Kevin Bowersox


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.

like image 21
Gibin Ealias Avatar answered Sep 29 '22 17:09

Gibin Ealias