Add Class to Array of ID's in Javascript - javascript

I am using .map to get an array of element IDs (this is named 'ids') that have a 'default-highlight' class. After removing that class on mouseenter, I want to return that class to those specific id's (basically, leave it how I found it).
Two things are causing me trouble right now:
When I dynamically add data-ids to the td elements and then use those data-ids to create the array of 'ids' my mouseenter stops adding the 'HIGHLIGHT' class (NO idea why this is happening)
On mouseleave I can't loop through the 'ids' and return the 'default-highlight' class to the elements they originally were on
I figure I should be using something like this, but it obviously isn't working:
$.each(ids, function() {
$(this).addClass('default-highlight');
});
I have tried a number of things, but keep coming up short. I am attaching a link to a codepen.io where I use data-ids that are being dynamically added to the table (this one the mouseenter doesn't work) and a codepen one where I am using regular IDs for the default highlight and everything appears to work like it is supposed to be (It isn't, since I want to be using the dynamically generated data-ids and then the subsequently produced array to reapply those classes).
Both of these codepens have a gif at top showing how the interaction should work.
If anything is unclear, please let me know. Thanks for reading!

You need to add # before id selector
$.each(ids, function() {
$('#'+this).addClass('default-highlight');
});
or you can use common selector by the help of map() and join()
$(ids.map(function(i, v) {
return '#' + v;
}).join()).addClass('default-highlight');
or you can add # when getting the id's and then you just need to join them
var ids = $('.default-highlight').map(function(i) {
return '#'+$(this).data('id');
}).get();
...
...
...
$(ids.join()).addClass('default-highlight');

It seems like storing the IDs and using those is overkill when you can store a reference to the jQuery element directly:
$highlightCells = $('.default-highlight').removeClass('default-highlight')
And later give the class back:
$highlightCells.addClass('default-highlight')
Here's a codepen fork: http://codepen.io/anon/pen/ZbOvZR?editors=101

Use this way:
$.each(ids, function() {
$("#" + this).addClass('default-highlight');
});

Related

hasClass not working. I try to add class to div when "active-card" class appears on it. any ideas?

I try to add class to div when "active-card" class appears on it. Tried different solutions, can't make that stuff work. Any ideas?
jQuery(document).ready(function($){
if ($(".card").hasClass("active-card")) {
$(".card").addClass("card-opacity");
}
});
First I will assume some things in my answer.
1 – there are multiple .card elements on your page
2 – you only want to add the class ‘card-opacity’ to a single element on dom
That being said you need to go through every card element and check if that specific element has the active-card class. In this case I used the map() function to iterate each element, but you can use your favorite loop function to iterate through an array.
// First get all '.card' elements and iterate through them
$('.card').map((card, index) => {
// check if the card element has the class 'active-card'
if($(card).hasClass('active-card')) {
// if true add the class 'card-opacity' to that element
$(card).addClass('card-opacity');
}
})
as #ikik commented try to explain your question and give as much information as possible, so it’s easier for everyone to help

Im forcing to use getElementsByClassName()[] rather than getElementByClass()

I have 8 divs with id="div1","div2","div3".... and a class=divs. I also have a button with class="div1","div2","div3"......
When I click the button with id="div1", it will first remove all the class="selected" to all div that has a class="divs" then only the div with id="div1" will have the class selected. And so on.....
I want to use document.getElementByClass() for removing class but it don't work in my FIDDLE. :(
Instead, Im forced to use document.getElementsByClassName()[]. But it seems so hard to code since it requires me to put the specific arrays for the classname.
This is exactly I want to achieve FIDDLE
There is no getElementByClass for a reason: unlike id, class is not specified to be unique in a document. Which element would you get? No, you need the ability to get all of them. And if you get an array, that's solved by looping, not by repeating rows for each index:
However, your design is inefficient; and if you're already using jQuery, you can write it very tightly. This would be better:
<button class="divbuttons" data-div="div1">div1</button>
<button class="divbuttons" data-div="div2">div2</button>
...
then you can:
$(document).ready(function(){
$('.divbuttons').click(function() {
var div = $(this).data("div");
$('.divs.selected').removeClass('selected');
$('#' + div).addClass('selected');
});
});
This is an easy one. There is no document.getElementByClass
You have document.getElementById or document.getElementByClassName
There's no such thing as getElementByClass() because multiple elements can have the same class. There's getElementById() (elements have unique ids, or at least they're supposed to) and getElementsByClassName(), which returns an array of all elements that match the class specified.
try
$(document).ready(function () {
$("button[class^=div]").click(function () {
$(".divs.selected").removeClass("selected");
$("#" + $(this).attr("class")).addClass("selected");
});
});
DEMO

jQuery .addClass() and .removeClass() only applies to first instance of the element

I have the following code below:
<script type="text/javascript">
var $info = $('#thumb');
enquire.register("(max-width: 480px)", {
match: function() {
$info.removeClass('col-xs-6');
$info.addClass('col-xs-12');
},
unmatch: function() {
$info.removeClass('col-xs-12');
$info.addClass('col-xs-6');
}
}).listen();
</script>
I am using Enquire.js to dynamically add and remove css classes from elements.
The above code works but only for the first '#thumb'. I have about 12 elements which have the thumb id. Anyone know how I can apply it to all elements with the same ID
You have to use a class. ID's are unique so they can only apply it once. If you do: $('.thumb') then you will be fine.
It might be helpful for you to run your source through an html validator, which would help point out that it's not valid to have more than one element with the same id. Which is why it's only updating the first of your 12 elements.
Take a read through this http://css-tricks.com/the-difference-between-id-and-class/ is one quick reference that can hopefully explain the what/why/how of what's going on here.
#xxx is get by id. and you need to make sure this id is unique. If you want to get by class is .xxx for get by class, you will get it in array. So need to to use for-loop to addclass or removeclass

how to use jquery loop function to target many element with different ids

Currently, I have this code:
$(document).ready(function(){
// #filtertab-00 replace this with your element id
$('#filtertab-00 .box-content .es-nav .elastislide-next, #filtertab-00 .box-content .es-nav .elastislide-prev').click(function() {
// trigger lazy load
$("#filtertab-00 img.lazy").each(function(i) {
$(this).delay(150*i).fadeIn(1000, function() {
var src = $(this).attr("data-original");
$(this).attr('src',src);
});
});
});
});
and i want to use this function to target object names (id) as below:
filtertab-00
filtertab-10
filtertab-20
filtertab-30
filtertab-40
filtertab-50
filtertab-60
....
filtertab-90
Does anyone know how to use the loop function to get it work?
i just want this:
when i click pre or next button after i select a tab(name varies from filtertab-00 to filtertab-90),it will activate lazyloading for images at current selected tab.
any idea is welcome!
Perhaps you could use jQuery's attribute-starts-with selector. You can then just select all IDs that begin with filtertab- using jQuery like this:
$('div[id^="filtertab-"]').each( //magic goes here );
Note: This method is slow because it has to search the DOM for elements with IDs that meet the criteria, but it does the job. I've never noticed an appreciable latency.
This is solved through selector magic as filoxo described but since you want the images, here's another version involving find() to get your actual images.
$('div[id^="filtertab-"]').find("img.lazy").each(function(i) {
$(this).delay(150*i).fadeIn(1000, function() {
var src = $(this).attr("data-original");
$(this).attr('src',src);
});
});
In addition to that, check out the impressive list of jQuery selectors. They cover a lot of ground :)

select html object without id

Edit: one missing piece of information - I can't use the class selector because there are more divs with the same class. I already thought of that, but I forgot to mention it. I have no idea why my post got downvoted, but it seems awfully silly considering I provided a lot of information, gave it honest effort, and tried to be verbose with code examples. People on this forum are ridiculous sometimes.
I'm trying to set the id of a div that doesn't have one and there's no way I can give it one upon generation of the page. I've tried using jquery (.each, .contains, .find, .filter, etc.) and I can't seem to get it right. I know a ton of people have asked this question, but none of the answers made sense to me.
I have the ability to set the text (html?) of the div, but nothing else. It ends up looking like this:
<div class="dhxform_note" style="width: 300px;">Remaining letters: 500</div>
I want a handle to the div object so I can show the user how many more letters they can type by updating the text.
Using this:
$("div")
returns a list of all divs on the page. I can see the target div in the list, but I can't get jquery to return a single object.
I know it can also be done with something like this:
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++) {
if( /^Remaining letters/.test(divs[i].innerText) )
divs[i].id = "kudosMsgNote"
}
}
but I was hoping to complete this with a cleaner looking solution involving jquery. I also simply want to know how to do it with jquery, aesthetics not withstanding.
Use a class selector.
var theDivViaTheClass = $(".dhxform_note");
Class Selector (“.class”)
Description: Selects all elements with the given class.
version added: 1.0
jQuery( ".class" )
class: A class to search for. An
element can have multiple classes; only one of them must match.
For class selectors, jQuery uses JavaScript's native
getElementsByClassName() function if the browser supports it.
You seem to be targeting the <div> by its text. Try using the :contains selector:
$("div").filter(':contains("Remaining letters")').first().attr("id", "kudosMsgNote");
The .first() is to make sure you don't set the same id for multiple elements, in case multiple elements contain the text "Remaining letters".
Here's the docs for the :contains selector: http://api.jquery.com/contains-selector/
Be careful, the text you're looking for is case sensitive when using :contains!
Is that div the only one with the class dhxform_note? If so, you can use the class selector:
$('.dhxform_note').html();
With jQuery, you can specify any css selector to get at the div:
$(".dhxform_note").attr("id", "kudosMsgNote");
will get you this element as well.
Selecting on inner text can be a bit dicey, so I might recommend that if you have control over the rendering of that HTML element, you instead render it like this:
<div name="remainingLetters" class="dhxform_note" style="width: 300px">Remaining Letters: 500</div>
And get it like this:
$("[name=remainingLetters]").attr("id", "kudosMsgNote");
However, it's possible that you really need to select this based on the inner text. In that case, you'll need to do the following:
$("div").each(function() {
if ( /^Remaining letters/.test($(this).html()) ) {
$(this).attr("id", "kudosMsgNote");
}
});
If you cannot set id for whatever reason, I will assume you cannot set class either. Maybe you also don't have the exclusive list of classes there could be. If all those assumptions really apply, then you can consider down your path, otherwise please use class selector.
With that said:
$("div").filter(function() {
return /^Remaining letters/.test($(this).text())
}).attr('id', 'id of your choice');
For situations where there are multiple divs with the class dhxform_note and where you do not know the exact location of said div:
$("div.dhxform_note").each(function(){
var text = $(this).text();
if(/^Remaining letters/.test(text)){
$(this).attr("id", "kudosMsgNote");
}
});
EXAMPLE
If, however, you know that the div will always be the 2nd occurrence of dhxform_note then you can do the following:
$("div.dhxform_note").get(1).id = "kudosMsgNote";
EXAMPLE
Or do a contains search:
$("div.dhxform_note:contains('Remaining letters')").first().attr("id", "kudosMsgNote");
EXAMPLE

Categories

Resources