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
});
$(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.
The equivalent to $() or jQuery() in JavaScript is querySelector() or querySelectorAll() , which, just like with jQuery, you can call with a CSS selector.
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.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With