Cannot add class to element children - javascript

I'm trying to find an element in my HTML file based on its parent class name and then add a class to it. I've tried the solution in here but it won't work. also, I've tried to log the child class name to see if it's working but it will return undefined. My HTML file is something like this:
$(document).ready(function () {
console.log($(".grid-container").find(">:first-child").className);
$(".grid-container").find(">:first-child").toggleClass("search-controller");
});
.search-controller {
height: 100%;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ui-view="" class="grid-container ng-scope" style="">
<div ng-controller="citySearchController" ng-init="initialize()" class="ng-scope">
This is test data
</div>
</div>

To get the class name from jQuery object you have to use prop(). Try to set some style to the element so that the changes are visible (like color):
$(document).ready(function () {
console.log($(".grid-container").find(">:first-child").prop('class'));
$(".grid-container").find(">:first-child").toggleClass("search-controller");
});
.search-controller {
height: 100%;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ui-view="" class="grid-container ng-scope" style="">
<div ng-controller="citySearchController" ng-init="initialize()" class="ng-scope">
This is test data
</div>
</div>

Use addClass instead of toggleClass.toggleClass class will require an event like click to toggle the class.
$(document).ready(function() {
//console.log($(".grid-container").find(">:first-child").className);
$(".grid-container").find(">:first-child").addClass("search-controller");
});
.search-controller {
height: 100%;
border: 1px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ui-view="" class="grid-container ng-scope" style="">
<div ng-controller="citySearchController" ng-init="initialize()" class="ng-scope">Test
</div>
</div>

Related

how can i have one function be used on multiple items without creating seperate ids?

I have a game where there are balloons and each balloon has an onclick attribute which passes the id into a JS function to change the css.
Example:
<div id="balloon" class="container" onclick="popBalloon(this.id);"></div>
clicking this item will call the function below
function popBalloon(id){
document.getElementById(id).setAttribute("class","pop");
}
Problem is that I have multiples balloons of the same type, and instead of using a unique id for each one, I would like a way to determine the specific balloon being clicked using the same attribute names.
Is this possible?
If you pass event as the function parameter, you can use event.target to get the clicked Element
function popBalloon (event) {
event.target.setAttribute("class", "pop");
}
div {
margin-top: 10px;
height: 30px;
width: 30px;
border: 1px solid;
border-radius: 50%;
}
.container {
background-color: red;
}
.pop {
background-color: blue;
}
<div class="container" onclick="popBalloon(event);"></div>
<div class="container" onclick="popBalloon(event);"></div>
<div class="container" onclick="popBalloon(event);"></div>
<div class="container" onclick="popBalloon(event);"></div>
<div class="container" onclick="popBalloon(event);"></div>
Most of current answers suggest a function that defines click listener to a group of elements however you asked how to omit unique IDs where there are too many elements in a game. The simple answer is to pass OBJECT instead of ID to the function:
<div class="container" onclick="popBalloon(this);"></div>
and in the function:
function popBalloon(myobj){
myobj.setAttribute("class","pop");
}
Thats all.
Instead of manually entering the function signature in each balloon entry, handle it all in the javascript below. Throw all those balloons into a list. As Scott Hunter suggested, place each balloon in a class. Let's call it "balloon". Then add an event listener to each of those balloons. Here's a quick demo.
var balloonArray = document.querySelectorAll(".balloon");
balloonArray.forEach(function(item) {
item.addEventListener('click', function() {
item.innerText = "Clicked";
});
});
.container {
color: white;
height: 80px;
margin: 10px;
text-align: center;
}
<div class="container balloon" style="background-color: blue">Click me</div>
<div class="container balloon" style="background-color: red">Click me</div>
<div class="container balloon" style="background-color: green">Click me</div>
A good way to do it is add some class to all the balloons. Let's modify your code a bit
<div class="balloon"></div>
<div class="balloon"></div>
<div class="balloon"></div>
I have 3 of those divs with a class of balloon here. For the js we can do
Array.from(document.querySelectorAll(".balloon")).forEach(balloon=>{
balloon.addEventListener('click',()=>{
//On click event here
});
});
Here's how you add a click event to each of the balloon.

How do I toggle the background colors within a list of divs?

From a list of items, each in separate divs, the user can select and click only one. The background color should change on the selected one. If the user changes their mind, they can select another one, and the background color should change to the selected color and all the other divs on the list should change back to the default background color.
It's basically the same logic as a radio button on a form. Only one can be selected at a time.
How do I achieve this?
I have attempted to use the element.classList.toggle property. But it only handles each individually. Are there a javascript command(s) to handle this?
<style>
.teamSelected{
background-color: red;
border-radius: 4px;
}
</style>
<div onclick="toggleBackground(team1)">
<div id="team1">
</div>
</div>
<div onclick="toggleBackground(team2)">
<div id="team2">
</div>
</div>
<div onclick="toggleBackground(team3)">
<div id="team3">
</div>
</div>
<script>
function toggleBackground(teamnumber) {
var element = document.getElementById(teamnumber);
if (element) {
element.classList.toggle("teamSelected");
}
}
</script>
Thanks!
You are passing variables to the function, which don't exist. You need to put them in quotes, because the function is expecting strings.
const allDivs = document.querySelectorAll('.div');
function toggleBackground(teamnumber) {
var element = document.getElementById(teamnumber);
if (element) {
allDivs.forEach(function(el){
el.classList.remove('teamSelected');
});
element.classList.add("teamSelected");
}
}
.toggle > div {
width: 100px;
height: 100px;
border: 1px solid #000;
}
.teamSelected {
background-color: red;
border-radius: 4px;
}
<div onclick="toggleBackground('team1')" class="toggle">
<div id="team1" class="div">
</div>
</div>
<div onclick="toggleBackground('team2')" class="toggle">
<div id="team2" class="div">
</div>
</div>
<div onclick="toggleBackground('team3')" class="toggle">
<div id="team3" class="div">
</div>
</div>
seems like this is something you want?
let x = ('.something');
$(x).on('click', function(){
$(x).css('background','blue');
$(this).css('background', 'green');
});
.something{
width: 100px;
height: 100px;
background: yellow
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div class="something">
<div id="team1">
</div>
</div>
<div class="something">
<div id="team2">
</div>
</div>
<div class="something">
<div id="team3">
</div>
</div>

a robust way to toggle item display in Jquery

I want to toggle whether to display an item I should do the following:
$(item).css("display", "none")
$(item).css("display", "block")
But this method is not robust enough, given that the item might be "display: flex" or "display: table".
I think in react, I can just delete that element and re-render it when I need to, but is there any simple way to do that using jQuery besides directly modify the html to delete that element?
Thanks.
you should use toggleClass() in case you are working with flex then it would be a better approach to keep the flex properties in a separate class and add/remove or in easy words toggle the flex class if you want to hide or show that container with defaults set to display:none in a separate class, in this way either the container is flex or table it works either ways see the example below
$(".show").on('click', function() {
if ($(this).siblings('.my-item').css('display') == 'flex') {
$(this).siblings('.my-item').toggleClass('myflex');
} else {
$(this).siblings('.my-item').toggleClass('myTable');
}
})
.my-item {
display: none;
}
.myflex {
display: flex;
background-color: #f8f8f8;
}
.myTable {
display: block;
background-color: #d8d8d8;
}
.container {
margin-top: 10px;
border: 5px dashed #c8c8c8;
}
.show {
padding: 10px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<a class="show">TOGLLE THIS ITEM</a>
<div class="my-item myflex">1
</div>
</div>
<div class="container">
<a class="show">TOGLLE THIS ITEM</a>
<div class="my-item myflex">2
</div>
</div>
<div class="container">
<a class="show">TOGLLE THIS ITEM</a>
<div class="my-item myTable">TABLE DISPLAY
</div>
</div>
<div class="container">
<a class="show">TOGLLE THIS ITEM</a>
<div class="my-item myflex">3
</div>
</div>
<div class="container">
<a class="show">TOGLLE THIS ITEM</a>
<div class="my-item myflex">4
</div>
</div>
<div class="container">
<a class="show">TOGLLE THIS ITEM</a>
<div class="my-item myflex">5
</div>
</div>
You could also add a custom css class and switch them using below. This would also give a bit more control over styling.
$(item).addClass('display-none');
$(item).removeClass('display-none');
$(item).removeClass('display-none display-flex'); // For removing multiple classes
and for example the css properties would be like
.display-none{
display: none !important;
}
Why not just use jQuery's show/hide functions?
$(item).hide();
$(item).show();
hide function is roughly equivalent to calling .css( "display", "none" ), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. (from jQuery documentation)
$('#btnToggle').click(function(){
if($('#item').is(':visible'))
{
$('#item').hide();
}
else
{
$('#item').show();
}
$('#log').html("Current display state: " + $('#item').css('display'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnToggle">toggle</button>
<div id="item" style="display: flex;">
flex div
</div>
<div id="log">
</div>
You can do a
$(item).css("display", "none")
and assign the flex or table value of the display property to any custom attribute, e.g. $(item).attr("disp_prop","flex") and on returning back to display you can do a simple.
$(item).css("display", $(item).attr("disp_prop"))

Javascript - show a button inside of a DIV when clicked (and hide all others)

I have a list of DIVS that have buttons inside. By default, all buttons are hidden. When I click within a DIV area, the current button inside of this clicked DIV are should show (class='.db') AND all previously clicked/shown buttons should be hidden (class='.dn'). In other words, at any time there should be only one button (currently clicked) shown and all other should be hidden.
I want to use vanilla Javascript and tried this below, but it won't work. I feel there is some small error but don't know where.. Note - the DIVS and buttons don't have their own unique IDs (they only have the same CSS (.posted) classes.
PS - maybe it'd be better not to add this onClick="t();" to each DIV and use an 'addEventListener' function, but this is way too much for me ; )
CSS:
.dn {display:none}
.db {display:block}
.posted {
height: 50px;
width: 100px;
background-color: green;
border: 2px solid red;
}
HTML:
<div class="posted" onClick="t();">
<button class="dn">Reply</button>
</div>
<div class="posted" onClick="t();">
<button class="dn">Reply</button>
</div>
<div class="posted" onClick="t();">
<button class="dn">Reply</button>
</div>
JAVASCRIPT:
function t()
{
var x=document.getElementsByClassName("posted"),i,y=document.getElementsByTagName("button");
for(i=0;i<x.length;i++)
{
x[i].y[0].className="dn";
};
x.y[0].className='db';//make sure the currently clicked DIV shows this button (?)
}
You might want to read more about selector, how to select class, block level etc.
some link might be helpful:
CSS selector:
https://www.w3schools.com/cssref/css_selectors.asp
jQuery selector:
https://api.jquery.com/category/selectors/
Solution - Using jQuery:
$('.posted').on('click', function() {
//find all class called posted with child called dn, then hide them all
$('.posted .dn').hide();
//find this clicked div, find a child called dn and show it
$(this).find('.dn').show();
});
.dn {
display: none
}
.db {
display: block
}
.posted {
height: 50px;
width: 100px;
background-color: green;
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="posted">
<button class="dn">Reply1</button>
</div>
<div class="posted">
<button class="dn">Reply2</button>
</div>
<div class="posted">
<button class="dn">Reply3</button>
</div>
Solution - Pure js version:
//get list of div block with class="posted"
var divlist = Array.prototype.slice.call(document.getElementsByClassName('posted'));
//for each div
divlist.forEach(function(item) {
//add click event for this div
item.addEventListener("click", function() {
//hide all button first
divlist.forEach(function(el) {
el.getElementsByTagName('button')[0].classList.add('dn');
});
//show button of the div clicked
this.getElementsByTagName('button')[0].classList.remove('dn');
}, false);
});
.dn {
display: none
}
.db {
display: block
}
.posted {
height: 50px;
width: 100px;
background-color: green;
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="posted">
<button class="dn">Reply1</button>
</div>
<div class="posted">
<button class="dn">Reply2</button>
</div>
<div class="posted">
<button class="dn">Reply3</button>
</div>
You can do this with with plain JavaScript using Event Bubbling, querySelector and the element classList attribute like this.
Change your HTML to look like this:
<div class="posts">
<div class="posted">
<button class="dn">Reply</button>
</div>
<div class="posted" >
<button class="dn">Reply</button>
</div>
<div class="posted" >
<button class="dn">Reply</button>
</div>
</div>
Then use JavaScript like this:
var posts = document.querySelector('.posts');
var allPosted = document.querySelectorAll('.posted');
//clicks bubble up into the posts DIV
posts.addEventListener('click', function(evt){
var divClickedIn = evt.target;
//hide all the buttons
allPosted.forEach(function(posted){
var postedBtn = posted.querySelector('button');
postedBtn.classList.remove('db');
});
// show the button in the clicked DIV
divClickedIn.querySelector('button').classList.add('db')
});
You can find a working example here: http://output.jsbin.com/saroyit
Here is very simple example using jQuery .siblings method:
$(function () {
$('.posted').click(function () {
$('button', this).show();
$(this).siblings().find('button').hide();
});
});
https://jsfiddle.net/3tg6o1q7/

Select first div not in class name using jQuery

hello How do you find element not in this class name?
drop-area__itemPage
I use this but not working
$("#drop-area").children("div").find(".drop-area__item:not('.drop-area__itemPage:first')")
$("#drop-area").children("div").find(".drop-area__item")
div#page1.drop-area__item.ui-droppable.drop-area__itemPage
div#page2.drop-area__item.ui-droppable.ui-droppable-active
div#page3.drop-area__item.ui-droppable.ui-droppable-active
div#page4.drop-area__item.ui-droppable.ui-droppable-active
div#page5.drop-area__item.ui-droppable.ui-droppable-active
div#page6.drop-area__item.ui-droppable.ui-droppable-active
div#page7.drop-area__item.ui-droppable.ui-droppable-active
div#page8.drop-area__item.ui-droppable.ui-droppable-active
div#page9.drop-area__item.ui-droppable.ui-droppable-active
enter code here
Here is a snippet showing selection of first child which has one class and do not has another one:
$("#drop_area").find("div.class1:not([class~='class3']):first").css("border", "5px blue solid");
.class1, .class2, .class3{
display: inline-block;
margin: 20px;
width: 150px;
height: 80px;
}
.class1 {
background: teal;
}
.class2 {
background: tomato;
}
.class3 {
background: lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="drop_area">
<div class="class1 class3 class2">class1 class3 class2</div>
<div class="class2">class2</div>
<div class="class1 class2">class1 class2</div>
<div class="class3 class1">class3 class1</div>
<div class="class1">class1</div>
<div class="class2">class2</div>
<div class="class1 class2">class1 class2</div>
<div class="class3 class1">class3 class1</div>
<div class="class3">class3</div>
<div class="class2">class2</div>
<div class="class3 class2">class3 class2</div>
<div class="class3 class1">class3 class1</div>
</div>
<div class="result"></div>
So result jquery statement looks like:
$("#drop-area .drop-area__item:not('.drop-area__itemPage'):first")
First select all related elements, than exclude with class .drop-area__itemPage and than use .eq(0) to select first of them:
$('#drop-area div .drop-area__item.:not(.drop-area__itemPage)').eq(0);
I'm taking a bit of a guess at what you're trying to do, but if you want to find the first child div of drop-area that does not have the class drop-area__itemPage, you can do this:
$(function() {
$("#drop-area").find(".drop-area__item").not('.drop-area__itemPage').first().css({
'color': 'red'
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="drop-area">
<div id="page1" class=".drop-area__item ui-droppable drop-area__itemPage">1</div>
<div id="page2" class="drop-area__item ui-droppable ui-droppable-active">2</div>
<div id="page3" class="drop-area__item ui-droppable ui-droppable-active">3</div>
</div>

Categories

Resources