Find closest element by attribute - javascript

I have this vote snippet, and I'd like to add a disabled class to the other button than what the user press. For example if user vote + on id 1 post then the - button would get a disabled class, but not the id 2 ones.
<span class="pull-right">
+
<span id="votes-1">0</span>
-
</span>
<span class="pull-right">
+
<span id="votes-2">0</span>
-
</span>
I already tried several things like .closest().find() but i couldnt make it work.

Traverse up to the parent of the clicked .vote element.
Use .not() and this to exclude the clicked .vote element.
$('.vote').click(function() {
var parent = $(this).parent();
$(this).removeClass('disabled');
parent.find('.vote').not(this).addClass('disabled');
});
.disabled {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<span class="pull-right">
+
<span id="votes-1">0</span>
-
</span>
<span class="pull-right">
+
<span id="votes-2">0</span>
-
</span>

$('.vote').click(function() {
var parent = $(this).parent();
$(this).removeClass('disabled');
parent.find('.vote').not(this).addClass('disabled');
});

You can use several approaches.
The following jQuery code is the shortest one. It takes all siblings and filters them with selector. The only item in array will be another button:
$(".vote").click(function()
{
$(this).siblings(".vote").addClass("disabled");
});
You can also do it this way. It is searching globally through the attribute value. It is good if you will need to disable something else in a document by attribute id.
$(".vote").click(function() {
var id = $(this).data('id');
$(".vote[data-id='" + id + "']").not(this).addClass("disabled");
});
Another option is traversing up to a parent, taking elements by selector and exlucing current one. Internally, it is almost the same as the first one.
$(".vote").click(function() {
$(this).parent().find(".vote").not(this).addClass("disabled");
});
Choose one which is the most preferrable.

Related

How to select an element with jQuery using a variable in "contains" and remove the nearest el with class Foo

I'm trying to select an element using a variable in the selector to remove the nearest element with class flag-container. However, the element isn't removed when I trigger the function.
function remove_div() {
let comment_pk = 1
$("div:contains('" + comment_pk + "')").closest('.flag-container').remove()
}
$('#trigger').click(function() {
remove_div()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div hidden class="comment-pk">1</div>
<div class="drilled-hierarchy">
<div class="flag-container">
To be removed
</div>
</div>
<button id="trigger"> Remove </button>
The issue in your logic is that closest() travels up the DOM along ancestor elements. The .flag-container you're looking to target is instead a child of a sibling to the original div.
Therefore you can use next()* and find() instead:
function remove_div() {
let comment_pk = 1
$("div:contains('" + comment_pk + "')").next('.drilled-hierarchy').find('.flag-container').remove()
}
$('#trigger').click(function() {
remove_div()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div hidden class="comment-pk">1</div>
<div class="drilled-hierarchy">
<div class="flag-container">
To be removed
</div>
</div>
<button id="trigger">Remove</button>
*using a selector string argument in the next() call is optional in this case, but saves unexpected bugs later. siblings() may also be appropriate depending on your exact use case.
In vanilla JS, will only find exact matches:
[...document.querySelectorAll('div')]
.find(d=>d.textContent===String(comment_pk))
.nextElementSibling
.querySelector('.flag-container')
.remove();

how to set unique id for every element in html using jQuery

i have lots of classes in my html but i want every class(or id if i have to change) be unique.here this code should work. i have lots of class="answer-to-q" in my code and when i click on specific one, that <div> should slide down not others.
<div style="text-align: right;margin: 20px 20px 0 0">
<p class="answer-to-q">please log in
<span uk-icon="icon: plus-circle"></span>
</p>
</div>
jquery:
$(".answer-to-q").click(function () {
$(".post-a-answer-div").slideDown("slow");
});
Ideally I think you should to set the IDs when you're generating the HTML, but if that's not possible, something like this could work? I'm using data attributes instead of IDs because that seems more appropriate but it could be modified to work with IDs if you really need to use 'em.
// Add data attributes
var count = 1;
$('.answer-to-q').each(function(){
$(this).attr('data-q', count);
$('body').find('.post-a-answer-div:not([data-a])').first().attr('data-a', count);
count++;
});
// Toggle on click
$('.answer-to-q').click(function(){
var target = $(this).attr('data-q');
$('[data-a="'+target+'"]').toggle();
});
Example:
https://codepen.io/anon/pen/xzaBgM

Class not working jQuery

So I more than one dynamicly generated elements with the same class name that I am trying to check input for in jQuery. Instead of it letting me click on both, it is just letting me click the first element generated.
Ex: I click on item_1 and it returns the item_1 id, but when I click on item_2 it doesn't return anyting.
HTML
<div id="item_1" class="resp"></div>
<div id="item_2" class="resp"></div>
JS - Jquery
$(".resp").on("click",() =>{
var id = $(".resp").attr("id");
console.log('attempting toggle' + id);
});
Firstly, you have to use normal function instead of arrow function (to avoid missing the context). Secondly - use this keyword to refer to the actually clicked element.
$(".resp").on("click", function() {
console.log('attempting toggle ' + this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item_1" class="resp">A</div>
<div id="item_2" class="resp">B</div>
This is because .attr('id') returns the value of the id attribute of the first matched element in the set.
Instead, use an old school function for the handler so the this value is equal to the clicked div, then get its id:
$(".resp").on("click", function() {
var id = $(this).attr('id');
console.log('attempting toggle ' + id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item_1" class="resp">First</div>
<div id="item_2" class="resp">Second</div>
What you're doing here is referencing the classname to obtain the id. This gathers the id of the first classname, which isn't what you desire. What you need to do is use the this keyword to correctly obtain the id.
After removing the arrow function and changing the internal code a bit, it should look like this:
$(".resp").on("click", function() {
var id = this.id;
console.log('attempting toggle: ' + id);
});
Also make sure you've correctly installed JQuery. Pick up your JQuery embed code from here.
Also remember to include your JQuery code before your JavaScript code.

jQuery - auto add toggle on element?

I have this code. Its for every single element. Is there a way to automate it? Because if I want to add element (job4 for example) I also need to add jQuery code.
$("#jobi1").click(function() {
$("#job1").fadeIn(300);
});
$("#jobi2").click(function() {
$("#job2").fadeIn(300);
});
$("#jobi3").click(function() {
$("#job3").fadeIn(300);
});
Give your job elements the same class and put the job identifier in a data-attribute, like this:
<button class="job" data-id="job1">job1<button>
<button class="job" data-id="job2">job2<button>
<button class="job" data-id="job3">job3<button>
And the javascript:
$('.job').on('click', function(){
var id = $(this).data('id');
$('#'+id).fadeIn(300);
});
Use a class and grab the ID from a data attribute
$(".job").on("click",function() {
$(this).data("target").fadeIn(300);
});
using
<div class="job" data-target="job1">...</div>

How to extract the "href" attribute value from within the closest list item

My site has a column of checkboxes with IDs in sequential order like "keepbox1", "keepbox2", etc. Each checkbox resides within a list item, along with a href attribute like this:
<li>
Title
<br>
<input id="keepbox1" type="checkbox" class="kboxes" name="keepbox1" />
<label for="keepbox1">Keep</label>
<div class="tinybox" alt="tinypic1" id="tinypic1" style="display:none;">
Content Here
</div>
</a>
</li>
There is also an element on the page that I use as button
<a><label class="getFiles" for="lightbox-two">Submit</label></a>
When a user clicks this button, I have a script that loops through each variation of keepbox to see if a user checked it. If a particular keepbox is checked, I'd like to extract the href attribute's value in that particular li.
So if a user had checked keepbox1 from the demo code above, I'd like it to alert back "http://iNeedThisUrl.com".
I'm using the following script which successfully identifies a checked keepbox, but it's returning "undefined" in the alert box. I'm guessing I'm not grabbing the attribute properly. Any ideas? Thank you!
<script type="text/javascript">
$(document).ready(function() {
$('.getFiles').click(function() {
for (i = 1; i <= 100; i++)
{
if ($("#keepbox" + i).prop('checked'))
{
var addressValue = $("#tinypic" + i).closest("li").attr("href");
alert(addressValue);
}
}
});
});
</script>
Two issues:
1) you have closing anchor tag </a> without opening anchor tag as next sibling of div in li. you need to remove it.
2) div elements #tinypic+n are siblings of anchor element. You need to use:
$("#tinypic" + i).siblings("a").attr("href");
or
$("#tinypic" + i).prevAll("a").attr("href");
or
$("#tinypic" + i).closest("li").find("a").attr("href");
$(".kboxes").each(function(){
if ($(this).prop('checked')) {
var addressValue = $(this).closest("a").attr("href");
alert(addressValue);
return false;
}
});

Categories