jquery not getting class name of elements - javascript

I have the following code but for some reason jQuery does not pick the elements class name, I understand that if the element has more than one class calling .attr('class') won't return them but the .hasClass('class-name') should be able to identify if the element has the class name.
My problem is that jquery returns class name as undefined(I got this from the line commented.).
How can I make the all other div children of the #parent, that do not have class the-one to have a yellow background.
$(document).ready(function()
{
var j = $('#parent> div').size();
for(var i =0;i<j;i++)
{
//alert($('#parent> div').children().eq(i).attr('class'));
if(!$('#parent> div').children().eq(i).hasClass('the-one'))
{
$('#parent> div').children().eq(i).css('background','yellow')
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id = "parent">
<div class = "one the-one">one</div>
<div class = "two">two</div>
<div class = "three">Three</div>
<div class = "four">Four</div>
</div>

The children() call is redundant as none of the div elements have any child elements. Remove that and the code works:
$(document).ready(function() {
var j = $('#parent> div').size();
for (var i = 0; i < j; i++) {
//alert($('#parent> div').eq(i).attr('class'));
if (!$('#parent> div').eq(i).hasClass('the-one')) {
$('#parent> div').eq(i).css('background', 'yellow')
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="parent">
<div class="one the-one">one</div>
<div class="two">two</div>
<div class="three">Three</div>
<div class="four">Four</div>
</div>
Also note that you can tidy the logic in your JS using each() with the this keyword to reference the element in the loop:
$('#parent > div').each(function() {
if ($(this).hasClass('the-one'))
$(this).css('background', 'yellow')
});

The problem is $('#parent> div') returns the div children of #parent so calling children() again does not return any elements.
You can use a simple jQuery selector instead of a loop like
$(document).ready(function() {
$('#parent> div:not(.the-one)').css('background', 'yellow')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="parent">
<div class="one the-one">one</div>
<div class="two">two</div>
<div class="three">Three</div>
<div class="four">Four</div>
</div>
But you can just use css for this, no need to use jQuery
#parent> div:not(.the-one) {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="parent">
<div class="one the-one">one</div>
<div class="two">two</div>
<div class="three">Three</div>
<div class="four">Four</div>
</div>

$(document).ready(function() {
$('#parent > div').each(function(){
var classtheone = $(this).hasClass('the-one');
if(!classtheone){
$(this).css('background-color', 'yellow')
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id = "parent">
<div class = "one the-one">one</div>
<div class = "two">two</div>
<div class = "three">Three</div>
<div class = "four">Four</div>
</div>
Try this way

Why not try a simpler method?:
$("#parent > div").not(".the-one").css("background", "yellow");
More info about jQuery's .not method...

Try this
$("#parent div").each(function(){
var me=$(this);
if(me.hasClass("the-one")) { me.css({"background-color" : "yellow"}); }
})

As written already in other answers, your children() call is the problem, I suggest using the following solution with each() as it is simpler
$(document).ready(function()
{
$('#parent div').each(function( i ) {
if ( !$(this).hasClass('the-one')) {
$(this).css('background','yellow');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id = "parent">
<div class = "one the-one">one</div>
<div class = "two">two</div>
<div class = "three">Three</div>
<div class = "four">Four</div>
</div>

Related

how to access elements inside a variable named div

var temp = $('#temp');
$('button').on('click', function(){
temp.html($('#wrap').html());
temp('.elmark').removeClass('elact'); // error
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>CLICK</button>
<div id='wrap'>
<div class='elmark elact'>R</div>
</div>
<div id='temp'></div>
how to access '.elmark' inside temp using temp?
var temp = $('#temp');
$('button').on('click', function(){
temp.html($('#wrap').html());
temp.find('.elmark').removeClass('elact');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>CLICK</button>
<div id='wrap'>
<div class='elmark elact'>R</div>
</div>
<div id='temp'></div>
You can use the second argument of the jQuery selector $() to specify the context. This way you'll find all elements which match the selector which are descendants of temp (ie the context):
var temp = $('#temp');
$('button').on('click', function() {
temp.html($('#wrap').html());
$('.elmark', temp).removeClass('elact');
});
.elact {
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>CLICK</button>
<div id='wrap'>
<div class='elmark elact'>R</div>
</div>
<div id='temp'></div>

tSort on jQuery object

I'm trying to sort the results of a jQuery selection with tSort.
HTML:
<div sort="2"></div>
<div sort="3"></div>
<div sort="1"></div>
<div sort="4"></div>
<div sort="6"></div>
<div sort="5"></div>
Javascript:
<script>
$sort_order = $('div').tsort({attr:'sort'});
</script>
I want the result to be: 1,2,3,4,5,6 in the jQuery object, not yet inserted into the page.
Is this possible with tSort, or should I write my own algorithm?
It is easier to do it if there is a wrapper of all the div elements.
HTML:
<div id="wrapper">
<div sort="2">2</div>
<div sort="3">3</div>
<div sort="1">1</div>
<div sort="4">4</div>
<div sort="6">6</div>
<div sort="5">5</div>
</div>
Javascript (with jQuery):
var $wrapper = $('#wrapper');
$wrapper.find('div').sort(function (a, b) {
return +a.getAttribute('sort') - +b.getAttribute('sort');
})
.appendTo($wrapper);
Working demo.
In response to #Tim's comment, you can place the elements that do not have the sort attributes at the back of the wrapper element easily, even without jQuery.
Assuming that this is your HTML:
<div id="wrapper">
<div style="color:red;">red color, without sort attribute</div>
<div style="color:red;" sort="7">red color (sort attribute=7)</div>
<div sort="2">2</div>
<div sort="3">3</div>
<div sort="1">1</div>
<div sort="4">4</div>
<div sort="6">6</div>
<div sort="5">5</div>
</div>
You can place the element(s) that do not have the sort attribute by having this as your Javascript:
// As shown earlier above,
var $wrapper = $('#wrapper');
$wrapper.find('div').sort(function (a, b) {
return +a.getAttribute('sort') - +b.getAttribute('sort');
})
.appendTo($wrapper);
// New code to add:
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++) {
if(divs[i].getAttribute('sort') == null || divs[i].getAttribute('sort') == undefined) {
divs[i].parentNode.appendChild(divs[i]);
}
}
Working demo.
clone it before using .tsort
$sort_order = $('div').clone().tsort({attr:'sort'});
DEMO

For each div with same class do something

I have some divs with same class. Inside this divs i added another div to put an ad.
Now i am trying to hide the ad div if the width of the div that holds my ad div is equal to 366px;
I tried the code bellow but it hides only my first ad div..
Example:
<div class="masterdiv">
<div id="myaddiv"></div>
</div>
<div class="masterdiv">
<div id="myaddiv"></div>
</div>
<div class="masterdiv">
<div id="myaddiv"></div>
</div>
and my jquery code is:
var adwidth = $(".masterdiv").width();
if (adwidth == 366){
$('#myaddiv').hide();
}
Thank you!
Because var adwidth = $(".masterdiv").width(); only returns the first value. The answer is in your title, you need to use each. Another issue is ids are SINGULAR, so you need to use a class
Using each:
$(".masterdiv").each( function() {
var elem = $(this);
var width = elem.width();
if (width == 366){
elem.find('.myaddiv').hide(); //use a class since only one element can have an id
}
});
Using filter:
$(".masterdiv").filter( function() {
return ($(this).width() == 366);
}).find('.myaddiv').hide();
The updated HTML:
<div class="masterdiv">
<div class="myaddiv"></div>
</div>
you should not use duplicate ids.use:
$('div .masterdiv').each(function(){
if($(this).width()==366){
$(this).find('div').hide();
}});
Try:
$('.masterdiv').each(function(){
if($(this).width()==386){
$(this).hide();
}
});
This is only doing the first div because you are using id's instead of classes. Since there can only be one id per page javascript stops after matching the first one. change to classes and you should be fine.
you are using same id's for different divs
Instead of id, give class name
<div class="masterdiv">
<div class="myaddiv">
</div>
</div>
<div class="masterdiv">
<div class="myaddiv">
</div>
</div>
<div class="masterdiv">
<div class="myaddiv">
</div>
</div>
$(document).ready(function () {
var adwidth = $(".masterdiv");
for (i = 0; i < adwidth.length; i++) {
if ($(adwidth[0]).attr("width") == 366) {
$(this).find('.myaddiv').hide()
}
}
});
$(".masterdiv").each(function(){
var current = $(this);
if(current.width() == 366) {
current.hide();
}
});
You have to change in this way:
$('#myaddiv', '.masterdiv').each(function() {
var width = $(this).width();
(width > 366) ? $(this).hide() : 0;
});
You can try on this live DEMO

jQuery basic: How to create a loop with this structure?

This is a really simple question but I'm not sure how to search for it on the internet.
I have an empty <div id="wrap"></div> that needs to end up looking as following:
<div id="wrap>
<div class="container">
<div class="apples"></div>
</div>
<div class="container">
<div class="banana"></div>
</div>
<div class="container">
<div class="orange"></div>
</div>
<div class="container">
<div class="grapes"></div>
</div>
</div>
In jquery I have:
$(#wrap).html(''); // need this bit
var fruitArray = ['apples','banana','orange','grapes'];
for (fruit in fruitArray) {
$('<div class="'+fruitArray[fruit]+'"></div>').appendTo('#wrap').doSomething();
}
Because I need the div with the fruitArray class to do something, I can't just wrap it around with the container class:
$('<div class="container"><div class="'+fruitArray[fruit]+'"></div></div>').appendTo...
How can I go about generating the container class in this situation?
The .wrap method returns the original set of elements for chaining purposes.
$('<div class="'+fruitArray[fruit]+'" />')
.appendTo('#wrap')
.wrap('<div class="container" />')
.doSomething();
Try this:
var fruitArray = ['apples','banana','orange','grapes'];
for (fruit in fruitArray) {
$('<div class="' + fruitArray[fruit] + '"></div>').appendTo('#wrap').wrap('<div class="container"></div>');
}
Example fiddle
var fruitArray = ['apples','banana','orange','grapes'];
for (fruit in fruitArray) {
$('<div class="'+fruitArray[fruit]+'" />').wrap('<div class="container" />').appendTo('#wrap').doSomething();
}
OR you can also do it like
var fruitArray = ['apples','banana','orange','grapes'];
for (fruit in fruitArray) {
$('<div class="'+fruitArray[fruit]+'" />').appendTo('#wrap').doSomething().wrap('<div class="container" />');
// this will work if the doSomething is a jquery/plugin method that is using chaining (usually they do)
}

Is there a jQuery selector to accomplish this task?

I have these 4 HTML snippets:
Siblings:
<div class="a">...</div>
<div class="b">...</div> <!--selected-->
<div class="b">...</div> <!--not selected-->
Wrapped 1:
<div class="a">...</div>
<div>
<div class="b">...</div> <!--selected-->
</div>
<div class="b">...</div> <!--not selected-->
Wrapped 2:
<div>
<div class="a">...</div>
</div>
<div>
<div class="b">...</div> <!--selected-->
</div>
<div class="b">...</div> <!--not selected-->
Separated:
<div class="a">...</div>
<div>...</div>
<div class="b">...</div> <!--selected-->
<div>...</div>
<div class="b">...</div> <!--not selected-->
<div>...</div>
<div class="b">...</div> <!--not selected-->
How can I, with jQuery, select the next .b element for any given .a element, regardless of nesting?
I want something like this:
$('.a').each(function() {
var nearestB = $(this)./*Something epically wonderful here*/;
//do other stuff here
});
Can you try this to see if it suits your case?
$(document).ready(function () {
var isA = false;
$('div.a, div.b').each(function () {
if ($(this).attr('class') == "a")
isA = true;
if ($(this).attr('class') == "b" && isA) {
$(this).css("background", "yellow");
isA = false;
}
});
});
Regards...
Got it!
var both = $('.a, .b');
$('.a').each(function() {
var nearestB = both.slice(both.index(this))
.filter('.b')
.first();
//do stuff
});​
How are you deciding which .a to select? Is there a .b for ever .a? Are you looping over each? You could use the index of the .a and simply select the corresponding .b.
$(".a").each(function(){
var index = $(".a").index(this);
var theB = $(".b").get(index);
});
Ok, here's a modified version of Padel's solution, that behaves slightly differently
var lastA = null;
$('.a, .b').each(function() {
if($(this).hasClass('a'))
{
lastA = $(this);
}
else if(lastA)
{
doStuff(lastA,this); //doStuff(a,b)
lastA = null;
}
});
$("div.a").nextAll("div.b")
Does this work?

Categories

Resources