This question already has answers here:
Getting the ID of the element that fired an event
(24 answers)
Closed 9 years ago.
I want to identify each element by it's name attribute. Each element has the same class and will ultimately contain differing dynamic information.
For example I would want the following code to alert the individual element's name value:
html:
<p class="pexample" name="0">this is p #1</p>
<p class="pexample" name="1">this is p #2</p>
<p class="pexample" name="2">this is p #3</p>
jquery:
$('p').on('click', function() {
if ($('p').attr('name') !== undefined) {
alert($('p').attr('name'));
}
})
Here is a jsfiddle.. http://jsfiddle.net/XG7nd/1/
This code however only alerts the initial elements name value. Help is greatly appreciated.
This should do:
$('p').on('click', function() {
var name = $(this).attr('name');// `this` here refers to the current p you clicked on
if (name ) {
alert(name);
}
})
While doing $('p').attr('name') this will always give you the name of the first item in the collection.
Demo
Try this:
$(document).on('click','p', function() {
alert($(this).attr('name'));
});
DEMO
You want to use $(this)
$('p').on('click', function() {
if($(this).attr('name') !== 'undefined') {
alert($(this).attr('name'));
}
});
This is occurring because you are getting the name attribute for the first <p> on every click. You need to specify the one that the event originated from:
$('p').on('click', function() {
if ($(this).attr('name') !== undefined) {
alert($(this).attr('name'));
}
})
Note, jQuery selectors return an array of matching elements. You must use the this keyword to get a handle on the element in the current context.
FIDDLE
Explanation
You keep looking for the p element even on click, so it'll select the first one it finds.
What your code says:
When p is clicked:
Find a p element and alert its attribute.
What you really want:
When p is clicked:
alert the clicked element's attribute
Solution
Select the attribute of this, which is the clicked element.
JSFiddle
JavaScript
$('p').on('click', function() {
if ($(this).attr('name') !== undefined) {
alert($(this).attr('name'));
}
})
Read more about the this keyword.
Related
I need to show an alert if there is a click anywhere except on .m1wrap div.
Why this doesn't work? Alert appears even if I click on .m1wrap
$(document).on("click", function(e) {
if (e.target.class !== "m1wrap") {
alert ("323");
};
})
In e.target there is no property class (it returns undefined), you can use property e.target.className (Note it returns all classes from class attribute), however in jQuery there is method .hasClass .
Also you can use classList with .contains method e.target.classList.contains('m1wrap')
$(document).on('click', function (e) {
if (!$(e.target).hasClass('m1wrap')) {
console.log('not m1wrap');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="m1wrap">m1wrap</div>
<p>test</p>
You need to use className to address the class attribute.
So either use jQuery's hasClass() or vanilla JS className.
Note: This example using className is only checking if the class does not equal "m1wrap", rather than does not contain "m1wrap".
$(document).on("click", function(e) {
if (e.target.className !== "m1wrap") {
alert ("323");
};
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="m0wrap">m0wrap</div>
<div class="m1wrap">m1wrap</div>
<div class="m2wrap">m2wrap</div>
There is no class in e.target, only className is available.
Code snippets:
$(document).on("click", function (e) {
if (e.target.className !== "m1wrap") {
alert("323");
};
})
But the following code snippets is the best way if there is multiple class names for an element.
$(document).on("click", function (e) {
if (!$(e.target).hasClass('m1wrap')) {
alert("323");
};
})
Event.target returns Element, which has not class property.
So you can use className property or getAttribute() method to get Element's class name.
If you want to use jQuery API, you can use hasClass() method
Try this,
<div>
<div class="m1wrap">
Non Clickable area
</div>
Clickable area
Clickable area
Clickable areaClickable areaClickable
Clickable areaClickable
Clickable area
</div>
JS
$(('body')).on('click',function(e) {
if ($(e.target).hasClass('m1wrap')) {
return false;
}
alert("hello");
})
DEMO
Is there a way to add some kind of listener for a type of html element? For example if i wanna call a function when the user clicks any p element
the easiest answer would be using addEventListener() if you want a specific html tag just like what i wanted in my question then you'll find the answer there ill paraphrase it here too
add this
<script>
document.addEventListener("click", function(e){
//your desired nodeName like : DIV , SPAN , LI etc
if(e.target && e.target.nodeName== 'DIV')
//add a function below to trigger
{alert('bingo')}
});
</script>
to the end of your document
by the way don't forget to use uppercase nodeNames or just put a toLowerCase() before it. cheers :)
Add the event listener to the window / document / document.body and check the type of the element and the types of its parents because if you have a <span> inside a <p>, clicking the span won't trigger the click in the paragraph.
document.addEventListener("click", function (eventArgs) {
var target = eventArgs.target;
var elementToLookFor = "p";
while (target !== null) {
if (target.tagName.toLowerCase() === elementToLookFor) {
// Do magic stuff with the paragraph
console.log(target);
}
target = target.parentElement;
}
});
This technique is called "event delegation."
Edit: Note that you cannot early return from the loop above. If your have nested paragraphs, i.e.
<p>
Hey,
<p>there!</p>
</p>
Having an early return will only call your event handler for the inner paragraph, whereas you said that you'd like the handler to be invoked on every paragraph which is why you need to traverse all the ancestors of the element.
I assume that you are looking for code along these lines:
var paras = document.getElementsByTagName("p");
// Loop through elements.
for(var i = 0; i < paras.length; i++) {
// Add listener.
paras[i].addEventListener("click",
function() {
// Execute function.
}, false);
}
I'd just select all the elements on the page and add eventListeners on them like so:
function addListeners(elementType, eventType, callback) {
Array.prototype.slice.call(document.querySelectorAll(elementType)).forEach(function (el, i) {
el.addEventListener(eventType, callback, false);
});
}
Above we use querySelectorAll to pick all the wanted elements, convert it to an Array (if you use es6, you can use Array.from) and then we loop through the array and add listeners with the wanted callback.
Here's an example: https://jsfiddle.net/a7en4d4s/
Look at this JSFiddle, and see if it works for you
<span>Click Yes</span><br/><br/>
<span>Click No</span><br/><br/>
<a>Clicked: <b id="result"></b></a>
<script>
$("span").click(function(){
var a = $(this).html();
$("#result").html(a);
});
</script>
This question already has answers here:
How to have click event ONLY fire on parent DIV, not children?
(12 answers)
Closed 8 years ago.
I'm looking for a jquery function doing the following :
if I click everywhere inside the div (but elements inside this div), the code is executed .
if I click in an html element inside this div , noting happens .
You need to test if the clicked target is this. Fiddle here: http://jsfiddle.net/ZBC43/
$('div').on('click', function(e) {
if (e.target !== this) return;
alert('div clicked');
});
The event is lopped through the element, until a element with a click element is found.
Solutions:
Test if the target element is the same as the delegateTarget
You set the event of the inner elements to a empty function
You need something like this (i try to find parent div with your class):
<div class='foobar'>
<span>child1</span>
<span>child2</span>
</div>
<span>child3</span>
<script>
$('.foobar').on('click', function(e) {
var testelem = $(e.target);
while (testelem != undefined && !testelem.hasClass('foobar')){
testelem = testelem.parent();
}
if (testelem != undefined && testelem.hasClass('foobar')) {
alert('code');
}
});
</script>
http://jsfiddle.net/eaVzx/
You can use tagName dom property to get current target element name.
TagName: Returns the name of the element.
HTML
<div id="myDiv" style='display:inline-block; width:300px;'><span style='display:inline-block;'>Hello Click here</span><br /><span style='display:inline-block;'>Click here</span></div>
Javascript
$(document).ready(function(){
$('#myDiv').click(function (e) {
if (e.target.tagName == "DIV") {
alert('Clicked on Div');
}
else{
alert('Clicked on Inner Element');
}
});
});
Try in fiddle
OR also use nodeName property to get current element.
NodeName: Returns the name of the current node as a string.
Try in fiddle 2
Try this:
$("div").click(function(e) {
if (e.target !== this) return;
alert("inside a div");
});
Each time a button is clicked i'm entering a function where I check if a listitem with specific classname exists. If it exists, then it has to be removed.
if($("ul#" + this.listClass + " li[class='errorlist']"))
{
console.log("error");
}
Now, it enters the function each time I click, even if it doesn't exist.
Thanks in advance.
If you want to check for class existing
if($('myElement').hasClass('myClassToCheckFor')){
//do stuff to my element here
}
if you want to check for element existing
if($('myElement.withMyClass').length > 0) {
//do stuff to my element here
}
So what you want to do is this (this is however not optimized for caching of jquery object but it demonstrates what you need to do).
$('button.myButton').click(function(){
if($('ul li').hasClass('monkey')){
$('ul li.monkey').remove();
} else {
alert("not found!");
}
});
See this fiddle
This could help
var test = document.getElementById('test') //returns a HTML DOM Object
var test = $('#test') //returns a jQuery Object
var test = $('#test')[0] //returns a HTML DOM Object
So you can use if($('#test')[0]) to check if the element exists in the DOM.
Example also to check if the element has a class
if($('#test')[0] && $('#test').hasClass("test")) {
$('#test').removeClass("test");
}
Some generated output can be as follows:
<div class="fivecol"></div>
<div class="sevencol">content</div>
if the div.fivecol is empty, I want to remove it and change the div.sevencol to a div.twelvecol
$('.fivecol').each(function() {
if ($(this).html() ==''){
$(this).remove().next('sevencol').removeClass('sevencol').addClass('twelvecol');
}
});
doesn't do the trick. Any ideas?
$('.fivecol:empty + .sevencol').toggleClass('sevencol twelvecol')
.prev()
.remove();
DEMO: http://jsfiddle.net/JY9NN/
$('.fivecol').each(function(i, div) {
if (!div.html().trim()) {
div.remove().next('sevencol').removeClass('sevencol').addClass('twelvecol');
}
});
basically I just fixed some syntax errors, and changed the this reference to the proper argument call. Let me know how that works.
Best,
-Brian
Try this,
$(function () {
$('.fivecol').each(function() {
if ($(this).html() =='') {
$(this).remove();
$('.sevencol').each(function(){
$(this).attr('class','twelvecol');
});
}
});
});
We could use a couple fancy selector tricks:
$(".fivecol:empty + .sevencol").attr("class", function(){
return $(this).prev().remove(), "twelvecol";
});
As you can probably guess, .fivecol:empty attempts to find an empty element with the class fivecol. It then proceeds to grab the sibling element, using +, which has the class .sevencol.
Once we have our .sevencol element, we set out to change its class value to twelvecol. Since we're in this function, we know that .fivecol:empty was found, so we can safely remove it. Lastly, we simply return the new class value to be assigned in the place of sevencol.
Demo: http://jsfiddle.net/cLcVh/1/