I need to take $('this') information from any element i click on the document.
I tried the following code:
$('body').click(function(){
var element = this.tagName; // or var element = $(this).prop('tagName');
alert(element);
});
The problem is that wherever i click i get only BODY element. If i click on a button or a div i want to get that element. How can i create something general to take every element i click ?
Because you are attaching your event handler to the body element, this will always be the body. Instead, interrogate the event.target property:
$('body').click(function(e){
var element = e.target.tagName;
alert(element);
});
Example fiddle
nodeName
$('body').click(function(e){
alert(e.target.nodeName);
});
http://quirksmode.org/dom/core/#t23
My advice is not to use tagName at all. nodeName contains all
functionalities of tagName, plus a few more. Therefore nodeName is
always the better choice.
it also looks like the performance is slightly better on some versions of chrome and firefox.
http://jsperf.com/tagname-vs-nodename/2
this always refers to the element where the event handler is assigned, not where the event originated (well, you can change it, but it's pretty unusual to do so). For that, you need Event.target:
$('body').click(function(event){
var element = event.target.tagName; // or var element = $(this).prop('tagName');
alert(element);
});
Related
I wanted to copy an entire row including its' siblings and contents on button click. When I click the button the element, it appears in the console but doesn't append to the page. This is my code:
It doesn't show any error messages. I've tried innerHTML/outerHTML or append() it doesn't work.
$(document).ready(function() {
$('#addSubFBtn').on('click', function() {
var itm = document.getElementById("trFb");
var wrapper = document.createElement('div');
var el = wrapper.appendChild(itm);
document.getElementById("tbFb").append(el);
console.log(el);
});
});
Seems like what you're trying to do is clone the item after you get it from your document. W3schools website explains how to accomplish this. Check out the link: https://www.w3schools.com/jsref/met_node_clonenode.asp
Once you clone the node, [appendchild] should work as intended
Not sure (as said without seeing related HTML) but i see flaw in your logic:
var itm = document.getElementById("trFb");
still exist on the document(so in the page) so you've to retrieve it before you want to add/move it to another place.
using .removeElement will return you removed element(or null if no element matche the selector) so correct script should be:
var itm=document.getElementById("trFb").parentNode.removeChild(document.getElementById("trFb"));
as shown here to remove element you've to use method on to parent element.
So you can add it to any other element existing.
For more specific use or element created in global JS variable (such an createElement not yet appended) you can see :document.createDocumentFragment(); as explained here https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment
I have a simple HTML table with ids in some cells:
<td id="x-11"><b>Is it a cell?</b> What a cell!</td>
Now I'd like to pass the ID to a JavaScript function triggered onclick:
const $tds = document.querySelectorAll('td[id]')
for (let i = 0; i < $tds.length; i++)
$tds[i].addEventListener('click', ev => console.log(ev.target.id))
It works as expected if I click an empty area or normal text within the cell. But if I hit the text inside the <b> element something strange happens: The browser says that the <b> element is the ev.target - although it has no listener whatsoever.
Can someone explain this behavior or offer a solution?
Update: As stated in the comments, Difference between e.target and e.currentTarget provides the answer (for ActionScript, but that doesn't make a difference here) but the question is different.
You need to use this or ev.currentTarget that always refers to the DOM element the listener was attached to, instead, the ev.target will refer to the element that fired the event, in this case, the DOM element that was clicked :
$tds[i].addEventListener('click', function(){
console.log(this.id)
});
//Or
$tds[i].addEventListener('click', ev => console.log(ev.currentTarget.id))
I am new in Jquery and I am trying to understand how event delegation work.
I am trying this:
$("#32298").on( 'click',function() { // event delegation
alert("df");
var imgs = document.getElementById("32298")[0].src;
alert(imgs);
});
When I click on the image with this Id I get the first alert but it doesn't work the second alert.
What am I doing wrong here?
Thank you.
If you want to perform event delegation then the second argument of the event handler function needs to be a selector to match the element that matches the one you want to be clicked.
$(document.body).on('click', "#32290", function(event) {
The problem with your code has nothing to do with event delegation. getElementById returns a single element (an id must be unique in the document), not a HTML Collection. (Compare with getElementsByTagName and getElementsByClassName which use the plural Elements.) It won't have a 0 property.
var imgs = document.getElementById("32298").src;
Since you're using jQuery, you can simply use the $(this) constructor, rather than document.getElementById():
$("#32298").on( 'click',function() {
alert("df");
var imgs = $(this).attr('src');
alert(imgs);
});
For what it's worth, this isn't event delegation by the way, it's just an event bound to an element.
If you must use vanilla JS to fetch the src attribute, you don't need to pass an index to the returned value of getElementById(), since this function returns a DOMObject, not an array. Update as follows:
$("#32298").on( 'click',function() {
alert("df");
var imgs = document.getElementById("32298").src;
alert(imgs);
});
It's also worth noting that IDs should be unique, so #32298 should reference a single element in the DOM. I don't know whether it's a typo, but it appears that you may have multiple elements with the same ID (since you use the variable name imgs - i.e. plural).
you can try this
$("#32298").click( function() {
alert("df");
var imgs = $(this).attr('src');
alert(imgs);
});
I want to get the innermost element on a certain cursor position, i.e.:
<div>
<div>
<span>Text</span>
</div>
</div>
If I point my mouse cursor over the text, I want to retrieve the span tag, not the outermost div which is the default of JavaScript's elementFromPoint(x,y).
(if it is of any help: I want to retrieve the element inside a JQuery keydown event handler)
A keydown event does not provide properties like .pageX and .pageY, so you cannot apply those values on document.elementFromPoint().
You need to have an event listener on your window or document.body and provide the event data information to a more public context, so you can access that data in your keydown handler.
Demo: http://jsfiddle.net/1ztf2p9b/
you can do something like this:
$('div').hover(function(element){
element.find('span').dosomestuff();
});
I hope it helps.
Demo: http://jsfiddle.net/mspocq9h/1/
var hoverEleme = null;
$('*').hover(function(){
hoverEleme = $(this);
});
$(window).on('keydown', function( e ) {
// Get hoverEleme here
$('span').css('color', 'black');
$(hoverEleme).closest('span').css('color','red');
});
Using jQuery's .closest() call with traverse up the element's ancestors to find the first element matching the selector, in this case the closest span.
Here there are no filters for what key was pressed, and it just sets the color to red so you can see it finds the one you're looking for.
I googled and googled and I concluded that it's very hard to get answer on my own.
I am trying to use jquery or JavaScript to get a property of clicked element. I can use "this.hash" for example - it returns hash value I presume.
Now I would like to get name of the class of clicked element.
Is it even possible? How? And where would I find this kind of information?
jQuery documentation? - All I can find is methods and plugins, no properties.. if its there - please provide me with link.
JavaScript documentation? - is there even one comprehensive one? again please a link.
DOM documentation? - the one on W3C or where (link appreciated).
And what is this.hash? - DOM JavaScript or jQuery?
In jQuery, if you attach a click event to all <div> tags (for example), you can get it's class like this:
Example: http://jsfiddle.net/wpNST/
$('div').click(function() {
var theClass = this.className; // "this" is the element clicked
alert( theClass );
});
This uses jQuery's .click(fn) method to assign the handler, but access the className property directly from the DOM element that was clicked, which is represented by this.
There are jQuery methods that do this as well, like .attr().
Example: http://jsfiddle.net/wpNST/1/
$('div').click(function() {
var theClass = $(this).attr('class');
alert( theClass );
});
Here I wrapped the DOM element with a jQuery object so that it can use the methods made available by jQuery. The .attr() method here gets the class that was set.
This example will work on every element in the page. I'd recommend using console.log(event) and poking around at what it dumps into your console with Firebug/Developer tools.
jQuery
$(window).click(function(e) {
console.log(e); // then e.srcElement.className has the class
});
Javascript
window.onclick = function(e) {
console.log(e); // then e.srcElement.className has the class
}
Try it out
http://jsfiddle.net/M2Wvp/
Edit
For clarification, you don't have to log console for the e.srcElement.className to have the class, hopefully that doesn't confuse anyone. It's meant to show that within the function, that will have the class name.
$(document).click(function(e){
var clickElement = e.target; // get the dom element clicked.
var elementClassName = e.target.className; // get the classname of the element clicked
});
this supports on clicking anywhere of the page. if the element you clicked doesn't have a class name, it will return null or empty string.
$('#ele').click(function() {
alert($(this).attr('class'));
});
And here are all of the attribute functions.
http://api.jquery.com/category/attributes/
You can use element.className.split(/\s+/); to get you an array of class names, remember elements can have more than one class.
Then you can iterate all of them and find the one you want.
window.onclick = function(e) {
var classList = e.srcElement.className.split(/\s+/);
for (i = 0; i < classList.length; i++) {
if (classList[i] === 'someClass') {
//do something
}
}
}
jQuery does not really help you here but if you must
$(document).click(function(){
var classList =$(this).attr('class').split(/\s+/);
$.each( classList, function(index, item){
if (item==='someClass') {
//do something
}
});
});
There's a way to do this without coding. Just open the console of your browser (f12?) and go to element you want. After that, hover or click the item you want to track.
Every change done on the DOM will be for a few seconds marked (or lightened) as another color on the console. (Watch the screen capture)
On the example, each time I hover a "colorItem", the 'div' parent and the "colorItem" class appears lightened. So in this case the clicked class will be 'swiper-model-watch' or 'swiper-container' (class of the lightened div)