JavaScript - Adding span to children? - javascript

So I got a code which should add span, if it doesn't exist on children, but at the moment it adds to only one and not to others, because "code" sees it already exists. How to do it, that if there will be new div, then it adds to that as well?
if($("#itemcart div").children().length > 0){
} else{
$("#itemcart div").append($("<span> X</span>"));
}

You need a correct Selector:
var spanLength = $("#itemcart div span").length;
if(spanLength > 0){
$("#itemcart div").append($("<span> "+(spanLength+1)+"</span>"));
} else{
$("#itemcart div").append($("<span> 1</span>"));
}

Don't know if i understood, anyway, assuming you have multiple div and you want to check if EVERY div has a child span you can do something like this:
$("#itemcart div").each(function(){
if( $(this).children().length > 0){
} else{
$(this).append($("<span> X</span>"));
}
});
This will iterate through every div. In this loop, you can use this to refers to the current div and check if it has or not a children span
See the example here: https://jsfiddle.net/3qkpLnd9/1/

check this code. Just edit it with your selectors, and it is ready to use:
$('p.click').on('click', function () {
var newDiv = document.createElement('div'),
span = document.createElement('span');
span.innerText = 'X';
newDiv.appendChild(span);
$('.container').append($(newDiv));
});
and real fiddle:
https://jsfiddle.net/nx1fuffc/

Related

Javascript search using show() and hide() and adding additional classes

I am using javascript to search through a group of divs while I type. It displays the divs if their title matches what is being typed in the search box and hides any that don't match.
I want to also make the displayed divs have a position of 'initial' instead of 'absolute' so that they move to the top of the page if they are being shown.
I have tried the code below (the line: $('.cbp-item').position='initial';) but it doesn't add the attribute.
I don't seem to get any js errors in the console either.
$( document ).ready(function() {
$('#societies_search').on('keyup',function(){
var valThis = $(this).val().toLowerCase();
if(valThis == ""){
$('.cbp-item').show();
$('.cbp-item').position='initial';
}
else {
$('.cbp-item').each(function(i,item){
var text = $(item).text().toLowerCase();
console.log($(item).find('a').text());
if(text.indexOf(valThis) >= 0) {
$(item).show();
$(item).position='initial';
}
else{
$(item).hide();
}
});
}
});
});
You can use .css() for this
$(item).css('position','initial');

JavaScript: Check if moving div has reached a certain point on screen

I want to check if a div has moved to a certain point. Here is my code that isn't working.
JS:
(function deathCondition() {
if (wordlist.offsetTop >= 500) {
alert('hey');
}
})();
I even tried it just being alone.
if (wordlist.offsetTop >= 500) {
alert('hey');
}
not sure if wordlist contains the id or class of the element, but anyway you need to store the id or class of the element:
var wordlist = document.getElementById('wordlist');
then find out the elements offset:
elOffset = wordlist.offsetTop;

Create my own Radio-like-button with a DIV?

I'm trying to make a site where users can create there own social networking buttons. (I know its been done but its mostly for practice). A part of the site will allow users to choose the shape of the buttons. Here is the HTML:
<div class="design" id="shape">
<div class="shapeSelect square" id="square"></div>
<div class="shapeSelect rounded" id="rounded"></div>
<div class="shapeSelect circle" id="circle"></div>
</div>
What I would like to do is add an event listener when the div is clicked. After it's clicked the class attribute would be changed to "selected." When another one would be click then the first clicked one would be cleared and the next one would be selected. Just like with radio buttons.
I am familiar with JavaScript and my idea was this:
window.onload = function () {
'use strict';
document.getElementById("square").addEventListener('click', function (e) {//adds the event listener
divArray = document.getElementById("shape");//Here is my first issue: an array is not returned
if (!(document.getElementById("square").getAttribute("class") == "shapeSelect square selected")) {// checks to make sure its not already selected
for (i = 0, count = document.getElementById("shape").length; i < count; i++) {// if it isn't go through the array
divArray[i]// and this is where i also get stuck. I Can't figure out how i would return the class attribute to be class="shapeSelect circle" instead of class="shapeSelect circle selected"
};
}
}, false);
}
A more simple version of scdavis41's answer:
$(document).ready(function(){
$('#shape > .shapeSelect').click(function(){
$('#shape > .shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});
I also put a selector that includes the control's main div id in case you want to put this control more then once in your page.
** EDIT **
If you absolutly want to use javascript and DOM try this:
document.getElementById("square").addEventListener('click', function (e) {
var divArray = document.getElementById("shape").getElementsByTagName("div"); //Get all the div child element of the main div
for (i = 0, count = divArray.length; i < count; i++) {
if(divArray[i].getAttribute("class").indexOf("selected") !== -1) { //check if the selected class is contained in the attribute
divArray[i].setAttribute("class", divArray[i].getAttribute("class").replace("selected", "")); // clear the selected class from the attribute
}
};
document.getElementById("square").setAttribute("class", document.getElementById("square").getAttribute("class").concat(" selected")); //select the square
}, false);
This is verbose, but you could use:
$(document).ready(function(){
$('#square').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
$('#circle').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
$('#rounded').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});
This is jQuery, which means you have to load the jQuery library, but putting this above your script tag:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
If you are looking for a pure JavaScript solution, you could try this:
if(option == 'add'){
element.className = element.className + ' selected';
element.onclick = function() {select(this.id, 'remove')};
element.innerHTML = '✓';
}
else if(option == 'remove'){
element.className = element.className.replace(/\bselected\b/,'');
element.onclick = function() {select(this.id, 'add')};
element.innerHTML = '';
}
JSFiddle: http://jsfiddle.net/hKePD/
**EDIT**
Or if you were looking for a checkbox to be always checked, you could try this: http://jsfiddle.net/hKePD/1/
Building on scadvis41's answer, this is much shorter:
$(document).ready(function(){
$('.shapeSelect').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});

Check if a specific hidden div exists and if not create one

I want to check if a specific hidden div exists and if not create one.
I do:
function myFunction(somestring) {
var myHiddenDiv = jQuery('<div id="js_method" style="display:none">');
...
myHiddenDiv.append(somestring);
}
The problem is this seems to create a new hidden div every time the function is called on the same page.
the hidden div just seems scoped to the function, whereas I want it scoped to the page.
Any tips.
tips please
Thanks.
Use length property:-
function myFunction(somestring) {
var myHiddenDiv;
if($("#js_method").length == 0){
myHiddenDiv = jQuery('<div id="js_method" style="display:none">');
$("body").append(myHiddenDiv);
}else{
myHiddenDiv = $("#js_method");
}
...
myHiddenDiv.append(somestring);
}
Why not just check by ID?
if (jQuery("#js_method").length == 0) {
var myHiddenDiv = jQuery('<div id="js_method" style="display:none">');
...
myHiddenDiv.append(somestring);
}

How to check if element has HTML in it before removing? jQuery

in a function I need to check if a (div, span, p) contains any .html elements in it before attempting to remove the html and add in new content.
Not sure how to do this...
I tried this, but not working:
// HERE below I tried to do a check to see if the div's have HTML, but did not work
if ($('.'+rowName+' div').html) {
$('.'+rowName+' div').html.remove();
$('.'+rowName+' span').html.remove();
$('.'+rowName+' p').html.remove();
}
Full function
// Create the Role / Fan rows
function rowMaker (rowName, roleName) {
//alert(rowName+' '+roleName);
// HERE below I tried to do a check to see if the div's have HTML, but did not work
if ($('.'+rowName+' div').html) {
$('.'+rowName+' div').html.remove();
$('.'+rowName+' span').html.remove();
$('.'+rowName+' p').html.remove();
}
// Blue button
$('.'+rowName+' div').append(roleName);
$('.'+rowName+' div').attr('id', 'blue-fan-'+roleName);
var blueButton = ('blue-fan-'+roleName);
console.log('blueButton = '+blueButton);
// Genres
$('.'+rowName+' span').append(roleType);
// Tags
$.each(role_Actor, function(index, item) {
$('.'+rowName+' p').append(item+', ');
});
$('#'+blueButton).click(function () {
console.log('clicked blue button');
// clears the role_Actor to be used to recapture checkboxes
role_Actor = [];
console.log('role_Actor = '+role_Actor);
//$('#modal-'+roleId).modal();
$('#modal-'+roleId).modal({persist:true});
return false;
});
}
html is a method not a property, you need to use (), then you can use length property of String object for checking the length of the returned html string:
if ( $.trim( $('.'+rowName+' div').html() ).length ) {
// $('.'+rowName).find('div, p, span').remove();
$('.'+rowName).find('div, p, span').empty();
}
Note that if you want to change the HTML content of an element, there is no need to remove the current html content of it. html method overrides the current html content.
Check the children length.
if($('.'+rowName+' div').children().length > 0)
You can use .html() for this (and accounting for whitespace):
var $row = $('.rowName');
if (!$row.find('div').html().trim().length) {
$row.find('div, span, p').empty();
}
Try
if ($('.'+rowName+' div').html().length > 0) {
$('.'+rowName+' div').empty();
$('.'+rowName+' span').empty();
$('.'+rowName+' p').empty();
}
Plain Vanilla JavaScript should do the trick too.
if(document.querySelectorAll('.'+rowName+' div')[0].childElementCount > 0){
console.log("found");
}
Do it like this:
var elementExists = $('.'+rowName+' div').html();
if (elementExists) { ... }

Categories