How can I use getElementsByClassName with jQuery selector :not() selector - javascript

I'm trying to select and click on elements with the class ".foo" that do not contain the class ".bar".
I'd like to use code like this but it isn't working:
var inputs = document.getElementsByClassName('foo:not(bar)');
for(var i=0; i<inputs.length;i++) {
inputs[i].click();
}
Thanks for help!

You can try to use querySelectorAll:
var inputs = document.querySelectorAll('.foo:not(.bar)');
Or as you have jquery in your tags:
$('.foo:not(.bar)').each( function() {
$( this ).click();
});

You can use the .filter() function to first select all foos without bars:
JSFiddle
CSS
.foo, .bar{
padding:20px;
font-weight:bold;
}
jQuery
// get all foos and begine filtering
$('.foo').filter(function(){
// show what class each div has
$(this).text($(this).attr('class'));
// translates into: IF bar not exist then return this element
return !$(this).hasClass('bar');
// color the divs yellow
}).css('background-color','yellow');
HTML
<div class='foo'></div>
<div class='foo bar'></div>
<div class='foo bar'></div>
<div class='foo'></div>
<div class='foo'></div>
<div class='foo bar'></div>
<div class='foo'></div>
<div class='foo bar'></div>

Related

Use variable as selector in function

On click, I want to get the name of the closest div and then look for all div's, that have this name attribute and add a class to them.
Here is my code:
HTML:
<div class="wrapper">
<div class="container" name="button1">
<div class="button">this is p #1</div>
</div>
</div>
<div name="button1">
somewhere else
</div>
JS:
$('.wrapper').on("click", '.button', function() {
var attrname = $(this).closest('.container').attr('name');
$("div[name=attrname]").each(function() {
$(this).addClass("classtobeadded");
});
});
But it is not working. So, how can I use the variable in here:
$("div[name=attrname]").each(function()
Here is the fiddle:
There's a few issues with your logic. Firstly the .container element does not have the name attribute, the .button does, so you don't need to use closest(). Secondly, you need to concatenate the actual name value in to the selector. Lastly div elements do not have a name attribute so the HTML is invalid. If you want to store custom meta-data on an element use a data attribute instead.
Also note that you don't need the each() loop, you can just call addClass() on the collection selected with the data-name attribute. Try this:
$('.wrapper').on("click", '.button', function() {
var attrname = $(this).data('name');
$('div[data-name="' + attrname + '"]').addClass("classtobeadded");
});
.classtobeadded {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="container">
<div class="button" data-name="button1">this is p #1</div>
</div>
</div>
<div data-name="button1">
somewhere else
</div>
You have to concatenate it properly,
$(`div[name=${attrname}]`).each(function() {
And by the way, when looking at your code there is no attribute available in the closest div with a class .container. Check that as well.
$("div[name=" + attrname + "]").each(function() {})
or
$(`div[name=${attrname}]`).each(function() {})

How do I store multiple divs with toggleClass in localStorage?

I'm trying to add localStorage to the toggleClass function in jQuery, so that multiple divs with the .selected css class stay .selected when reloading or closing the browser. The toggleClass seems to work, but I can't seem to get the localStorage to work. What am I doing wrong?
Here's the fiddle.
JS:
$(function(){
$('.mix').click(function() {
window.localStorage.setItem('test',$(this).toggleClass('selected'));
});
if(localStorage.getItem('test')){
$(this).toggleClass('selected');
}
});
HTML:
<div id="box" class="p001 mix">Div 1</div>
<div id="box" class="p002 mix">Div 2</div>
Thanks in advance.
You need to uniquely identify each div element, here in example I have used data-* prefixed custom attributes. On page load you need to iterate the objects and target the elements on which the value of key is set to true
HTML
<div data-id="1" class="p001 mix">Div 1</div>
<div data-id="2" class="p002 mix">Div 2</div>
Script
$(function() {
$('.mix').click(function() {
$(this).toggleClass('selected');
var lsid = 'test' + this.dataset.id;
window.localStorage.setItem(lsid, $(this).hasClass('selected'));
});
$('.mix').each(function() {
var lsid = 'test' + this.dataset.id;
if (localStorage.getItem(lsid) && localStorage.getItem(lsid) == "true") {
$(this).addClass('selected');
}
})
});
Fiddle
Note: Identifiers in HTML must be unique, thus removed id="box" and used CSS based on class

How to add div dynamically inside a div by class - Jquery

I want dynamically add info div into every dynamic class.
HTML
<div id='container'>
<div class='dynamic'></div>
<div class='dynamic'></div>
<div class='dynamic'></div>
<div class='dynamic'></div>
</div>
I want like this.
<div id='container'>
<div class='dynamic'><div class="info">info</div></div>
<div class='dynamic'><div class="info">info</div></div>
<div class='dynamic'><div class="info">info</div></div>
<div class='dynamic'><div class="info">info</div></div>
</div>
JS FIDDLE
You can use $.wrapInner method
$(".dynamic").wrapInner('<div class="info">info</div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="dynamic"></div>
<div class="dynamic"></div>
<div class="dynamic"></div>
<div class="dynamic"></div>
</div>
To add an info div into every class using jQuery, simply use:
$( ".dynamic" ).append( "<div class='info'>info</div>" );
The JSFiddle demonstrates it.
If you want to continually check for .dynamic classes, you can use something like this:
$(document).ready(setInterval(function(){
$( ".dynamic" ).append( "<div class='info'>info</div>" );
}, 1000));
In the above case, you are checking for .dynamic classes every 1000ms (1 second).
Hope this helps.
Try using append():
$('.dynamic').append($('<div/>', { class: 'info' }).html('info'));
Update your fiddle:
http://jsfiddle.net/4cncLor7/2/
If your .dynamic div already contains content and you want to at the .info div at the beginning use prepend():
$('.dynamic').prepend($('<div/>', { class: 'info' }).html('info'));
I have updated it. Please check and give me feedback.
http://jsfiddle.net/4cncLor7/4/
jQuery('.dynamic').html('<div class="info">info</div>');
You could do something like this:
$('.dynamic').each(function() {
var newDiv = $('div');
newDiv.addClass('info');
newDiv.html('info');
//inject the new div
$(this).append(newDiv);
});
check this code : Example
Javascript:
var vof=$("#box1").val();
//$(".result-box").text(vof);
var e = $('<div class="result-box">'+vof+'</div>');
$('#box').append(e);
HTML :
<div id="box">
<!--<div class="result-box" id="rbx"></div>-->
</div>
here i am creating dynamic div so that every time button is clicked it create new div and you can add attribute id to them separately

jQuery check divs has a class and unwrap if no other class

I have two div's and what I am trying to do is loop through all the divs to check if the div has a class jsn-bootstrap3, I'm also trying to check to see if the div has any other classes, if it doesn't then I'd like to remove the jsn-bootstrap3 div so that the child content is whats left.
<div class="jsn-bootstrap3">
<div class="wrapper">
Div one
</div>
</div>
<div class="jsn-bootstrap3 block">
<div class="wrapper">
Div two
</div>
</div>
$('div').each(function() {
if ($(this).hasClass()) {
console.log($(this));
var class_name = $(this).attr('jsn-bootstrap3');
console.log(class_name);
}
});
jsFiddle
You can try something like
$('div.jsn-bootstrap3').removeClass('jsn-bootstrap3').filter(function () {
return $.trim(this.className.replace('jsn-bootstrap3', '')) == ''
}).contents().unwrap();
Demo: Fiddle
use the class selector to find div's with class jsn-bootstrap3 because we are not goint to do anything with others
use filter() to filter out div's with any other class
use unwrap() with contents() to remove the wrapping div

Mixing CSS & Javascript Eventhandlers

I'd like to be able to assign the same event handler to a number of different div elements. Each element will have a unique style.
I registered the eventhandler like so:
<script type="text/javascript">
function add_something() {
document.getElementById('manipulate').onclick = do_something;
}
function do_something(e) {
this.style.property = value;
}
window.onLoad = add_something;
</script>
So I can assign an event handler to an element like so:
<div id="manipulate"></div>
The problem is that I want to assign that handler to several elements, each with a unique style, and I want to use CSS to do it. but i'm not sure how to do that.
Eventually, I want something that looks like this:
<style>
#element1{...}
#element1{...}
#element1{...}
</style>
.....
<div id="element1" class="manipulate"></div>
<div id="element2" class="manipulate"></div>
<div id="element3" class="manipulate"></div>
Is this possible? Thanks
Event delegation?
HTML:
<div id="wrap">
<div id="element1" class="manipulate">First element</div>
<div id="element2" class="manipulate">Second element</div>
<div id="element3" class="manipulate">Third element</div>
</div>
JavaScript:
var wrap = document.getElementById('wrap');
wrap.onclick = function (e) {
var elem = e.target;
elem.style.color = 'red';
};
Live demo: http://jsfiddle.net/VLcPw/
You can select elements by class in modern browsers, or just use jQuery and know it works everywhere.
$(document).ready(function(){
$('.manipulate').click(function(){alert('Hello.')});
//or .hover/any other event.
});
jQuery events.
Perhaps a more relevant example?
$('.manipulate').click(function(){
$(this).addClass( 'whateverClass' );
//or
$(this).css('color', 'red');
});
Why are you not giving jquery a try?
With jquery you should just need this to bind the same click event to all corresponding elements:
$("div.manipulate").click(function(e) {
$(this).css(property, value);
});
property has to replaced with a valid css property, value with a correct value, of course.

Categories

Resources