How to get class of item selected in jquery? - javascript

I have 2 images (.field-img) , wrapped in a container (.group-container),
each of the images are in a unique field id, so my tpl is broken down into
<div class=group-container>
<div id=field1>
<div class=field-img>
</div></div>
<div id=field2>
<div class=field-img>
</div></div>
</div>
my js is
$(".group-container .field-img").click(function() {
alert(".group-container .field-img");
what I would like is to detect automatically if the image belongs to field1 or field2.
So I could alert (".group-container .field1/2 .field-img");
How would I do this?
Thanks for any help

$(".group-container .field-img").click(function() {
var field=$(this).parent().attr('id');
});

An alternative to Izzey's solution is to use .closest with an attribute starts with selector (or classname because it would be more appropriate for those divs to have a common class)
$(".group-container .field-img").click(function() {
var field = $(this).closest("[id^=field]")[0].id;
});
or, with a common classname,
html
<div class=group-container>
<div class="field" id=field1>
<div class=field-img>
</div></div>
<div class="field" id=field2>
<div class=field-img>
</div></div>
</div>
js
$(".group-container .field-img").click(function() {
var field = $(this).closest(".field")[0].id;
});

$(".group-container .field-img").click(function() {
var field = this.parentNode.id;
alert (".group-container ." + field + " .field-img");
});

$(".group-container .field-img").each(function() {
$(this).click(function(){
var fieldid=$(this).parent().attr('id');
});
});

Since one element is inside the other, the click will propagate up anyway, so you could always just bind the click to the parent element and do :
$('div[id^="field"]').on('click', function() {
alert(".group-container "+this.id+" .field-img");
});
FIDDLE
or even get them all dynamically:
$('div[id^="field"]').on('click', function(e) {
alert('.'+this.parentNode.className+" "+this.id+" ."+e.target.className);
});
FIDDLE
​

Related

How to get children id when I click the parent?

<div class="big" onclick="dataadd()">
<div id="a">child1</div>
<div id="b">child2</div>
</div>
When I click the div with class="big" tag, I wanna get the children's id or text.
I tried all several methods, but I can't handle it. Anyone know how to do it? Javascript or Jquery doesn't matter.
Thank you very much!
You can pass your clicked element by dataadd(this);
You may wonder how this comes inside the method. adding this keyword like above will refer to the current element.
Then using that element, you can find children and with each you can grab other details by loop through the children.
function dataadd(ele){
var children = $(ele).find('div');
children.each(function(idx, element){
console.log($(element).attr('id'));
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="big" onclick="dataadd(this)">
<div id="a">child1</div>
<div id="b">child2</div>
</div>
Use children() to selecting childs of element and use map() to mapping elements to id attribute.
$(".big").click(function(){
var ids = $(this).children().map(function(){
return this.id;
}).toArray();
console.log(ids);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="big">
<div id="a">child1</div>
<div id="b">child2</div>
</div>
Also you can use simpler code as shown in bottom
$(".big").click(function(){
console.log(
$('> *', this).map((i, val) => val.id).toArray()
);
});
For a more modern way with ES6:
document.querySelector(".big").addEventListener('click', function(e){
[...e.target.children].forEach(function(child){
const { id, innerText } = child;
console.log(id, innerText);
})
})
You can pass the context using this and use querySelectorAll to get the div and then its id
function dataadd(elem) {
elem.querySelectorAll('div').forEach(function(item) {
console.log(item.id)
})
}
<div class="big" onclick="dataadd(this)">
<div id="a">child1</div>
<div id="b">child2</div>
</div>
function dataadd(){
$(this).children().each(function(){
console.log($(this).attr('id'));
})
}
This code will print ids of big div.

Targeting Multiple Elements with One Function

I have a function that assigns dynamic classes to my div's. This function is a that runs on the page. After the page loads, all 10 of my primary 's have classes ".info1" or ".info2" etc...
I am trying to write a Jquery function that changes the class of the div you click on, and only that one. Here is what I have attempted:
$(".info" + (i ++)).click(function(){
$(".redditPost").toggleClass("show")
});
I have also tried:
$(".info" + (1 + 1)).click(function(){
$(".redditPost").toggleClass("show")
});
And
$(".info" + (i + 1)).click(function(){
$(".redditPost").toggleClass("show")
});
EDITED MY HTML: DIV RedditPost is actually a sibling to Info's parent
<div class="listrow news">
<div class="newscontainer read">
<div class=".info1"></div>
<div class="redditThumbnail"></div>
<div class="articleheader read">
</div>
<div class="redditPost mediumtext"></div>
</div>
My issue is two fold.
The variable selection for ".info" 1 - 10 isn't working because i doesn't have a value.
If I did target the correct element it would change all ".redditPost" classes instead of just targeting the nearest div.
Try like this.
$("[class^='info']").click(funtion(){
$(this).parent().find('.redditPost').toggleClass("show");
});
Alternative:
$('.listrow').each(function(){
var trigger = $(this).find("[class^='info']");
var target = $(this).find('.redditPost');
trigger.click(function(){
target.toggleClass("show");
});
});
Try this
$("div[class*='info']").click(function(){
$(this).parent().find(".redditPost").toggleClass("show")
});
Explanation:
$("div[class*='info'])
Handles click for every div with a class containing the string 'info'
$(this).parent().find(".redditPost")
Gets the redditPost class of the current clicked div
Since the class attribute can have several classes separated by spaces, you want to use the .filter() method with a RegEx to narrow down the element selection as follows:
$('div[class*="info"]').filter(function() {
return /\binfo\d+\b/g.test( $(this).attr('class') );
}).on('click', function() {
$(this).siblings('.redditPost').toggleClass('show');
});
.show {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="listrow news">
<div class="newscontainer read">
<div class="info1">1</div>
<div class="redditThumbnailinfo">2</div>
<div class="articleheader read">3</div>
<div class="redditPost mediumtext">4</div>
</div>
</div>

toggling div and adding and removing class

i have some divs i wanna toggle i am able to toggle but unable to remove classes when ever i click on the next div
index.php
<div id="menu_top1" class="menu_top1">LINK 1</div>
<div id="menu_top" class="menu_top">LINK 2</div>
<div id="content_area1" style="display:none;">
THIS IS LINK 1
</div>
<div id="content_area2" style="display:none;">
THIS IS LINK 2
</div>
Jquery.js
$('#menu_top1').click(function() {
$('#content_area1').toggle('slow', function() {
$('.menu_top1').toggleClass('active');
});
});
Here is a Fiddle https://fiddle.jshell.net/kunz/t5u6mcmn/
if you are trying to show corresponding content_area when you click on link and make the link active? you can check this
fiddle
i saw you using same id for multiple elements.just edited them.
still you want same id for all elements(strictly not recommended) check this fiddle
check this updated fiddle
$('.menu_top').click(function() {
var index = $( this ).index() + 1;
console.log(index);
$('[id^="content_area"]' ).hide();
$('#content_area' + index ).toggle('slow', function() {
$('.menu_top').toggleClass('active');
});
});

jQuery mouse leave enter hide show

Below is my jQuery:
$(".notificationfeedlist li").live('mouseleave', function() {
IF(NOT (MOUSE OVER AN ELEMENT WITH ID INFO))$('#info').hide();
});
And here is the HTML I am applying this jQuery to:
<div id="info">
<div class="arrow-right2"></div>
<div class="arrow-right"></div>
<div class="scrollerdiv"></div>
</div>
What should I replace IF(NOT (MOUSE OVER AN ELEMENT WITH ID INFO)) with to achieve hiding elements that do not have an ID of "info"?
$(".notificationfeedlist li").live('mouseleave',function(e){
if (e.target.id != "info") {
$('#info').hide();
};
});
You should change it to class="info" and then check with jQuery .hasClass();
Just trying to help: there are no lis in your code; just divs. That could be your problem.

How to add a class in a div somewhere else in the DOM with jQuery?

How can add class .jokjok in the div next of input[bdate]?
Example: http://jsfiddle.net/cLNJE/1/
This code did not work for me:
<button>Click Me</button>
<div class="pa_row mediumCell">
<div class="column">
<input type="text" name="expass">
</div>
<div class="column">
<div class="auto_box2">
<input type="text" name="bdate">
<div></div>
</div>
</div>
<div class="column">
<input type="text" name="old">
</div>
</div>
$('button').live("click", function () {
$('input[bdate]').closest('.pa_row ').find('auto_box2 div').removeClass().addClass('jokjok');
//alert('click is ok')
});
I think you need to specify which attribute you want to use for selection of the right input:
$('input[name="bdate"]');
This worked for me:
$('button').live("click", function () {
$('input[name="bdate"]').closest('.pa_row').find('div.column div.auto_box2 div').first().removeClass().addClass('jokjok');
});
See: http://jsfiddle.net/cLNJE/7/
the easy ways is:
Add id attribut to div
<div id="someid"></div>
$('button').live("click", function () {
$('#someid').addClass('jokjok');
});
Or
Create new whole div
$('button').live("click", function () {
$('input[name="bdate"]').after('<div class="jokjok"></div>');
});
Some of your selectors are not quite right,
$('input[bdate]')
should be
$('input[name=bdate]')
this will select the input with a name attribute of 'bdate' your previous selector was selecting all inputs that had an attribute of 'bdate'
find('auto_box2 div')
should be
find('div.auto_box2')
this will select the 'div' with a class of 'auto_box2'
Making those changes leaves us with this code -
$('button').live("click", function() {
$('input[name=bdate]').closest('.pa_row ').find('div.auto_box2').removeClass().addClass('jokjok');
alert('click is ok')
});
which should hopefully do what you want.
Updated fiddle - http://jsfiddle.net/ipr101/542ZW/1/
http://jsfiddle.net/cLNJE/8/
$('button').live("click", function () {
$('.auto_box2 input').siblings('div').addClass('jokjok');
});

Categories