Menu
  • HOME
  • TAGS

iterate through classes on same element

Tag: javascript,jquery

If I have a div which has multiple classes assigned to the class attribute, is it possible to iterate through them using the each() function in jQuery?

<div class="class1 differentclassname anotherclassname"><div>

Best How To :

In JavaScript, to get the list of classes, you can use

  • .className.split(' '), returns an Array
  • (HTML5) .classList, returns a DOMTokenList

In jQuery, you can use .prop() to get className or classList properties.

To iterate them, you can use:

  • A for loop, e.g. for(var i=0; i<classes.length; ++i)
  • (ES6) A for...of loop, e.g. for(var cl of classes).
  • (ES5) forEach, only for arrays, e.g. classes.forEach(fn)
  • (jQuery) $.each, e.g. $.each(classes, fn)

If you use classList but want to iterate using forEach, you can convert the DOMTokenList into an Array using

  • [].slice.call(classes)
  • (ES6) Array.from(classes)

show div only when printing

javascript,html,css

You need some css for that #printOnly { display : none; } @media print { #printOnly { display : block; } } ...

session value in javascript cannot be set

javascript,function,session

Javascript is a client-side language. Session are server-side component. If you want to update session when user does something on your page, you should create a ajax request to the server. Or maybe use some client side variables that, for some aspects, are similar to session (they will be forever...

Javascript sort array of objects in reverse chronological order

javascript,arrays,sorting

As PM 77-1 suggests, consider using the built–in Array.prototype.sort with Date objects. Presumably you want to sort them on one of start or end: jobs.sort(function(a, b) { return new Date(a.ys, a.ms-1) - new Date(b.ys, b.ms-1); }) ...

Cant submit form

javascript,php

Your PHP is checking if $_POST['submit'] contains a value. Your form does not contain a form element with the attribute name="submit", so therefore it fails and moves straight to the else statement. If you want to check if the form was posted then you should instead check for: if (!empty($_POST))...

writing jQuery instead of $ to access controls in a page

jquery

Yes you can write that way. jQuery.noConflict(); jQuery( "body" ).append('Hello'); Read it here...

Identifier starts immediately after numeric literal

jquery,ajax,razor

I think you have to include it with the ' mark Like this : var userID = '@User.Identity.GetUserId()';...

Click on link next link should be display on same page

javascript,php,jquery,html,css3

Ok, so i tried to decypher what you meant with your Question. To Clarify: He has this one page setup. inside the div Our Project, there are two Buttons or links Visit more. When clicked, he wants the About Section to be shown. All in all it is impossible for...

How To Check Value Of String

javascript,css,string,numeric

document.GetElementById("tombolco").style = "display:block"; That's not the right way. This is document.getElementById("tombolco").style.display = 'block'; Also note that it is getElementById, not with a capital G. Same with 'none',Rest of your code is fine. Fiddle...

Automatically calling server side class without

javascript,html,ajax

Trigger the click event like this: $('._repLikeMore').trigger('click'); ...

Set default value for struts 2 autocompleter

jquery,jsp,struts2,struts2-jquery,struts2-jquery-plugin

You should use the value attribute as suggested by @Choatech: value false false String "Preset the value of input element." The value specified, however, should be one of the keys listed in your cityList, not some random value. If the value you want to use is an header one, like...

Javascript change the souce of all images present inside a string

javascript,jquery

You can wrap your string into a jQuery-object and use the .find()-method to select the images inside the message-string: var msg = '<span class="user_message">hiiiiiii<img title=":benztip" src="path../files/stickers/1427956613.gif" /><img src="path../files/stickers/416397278.gif" title=":happy" /></span>'; var $msg = $(msg); $msg.find('img').attr('src', 'path_to_img'); $("#chat_content").append($msg); Demo...

How to remove legend from bottom of chart - amcharts

jquery,linechart,amcharts

In amcharts the legends are added manually, In your case jut remove the lines which add legends to the chart. For e.g., The legends are added as follows, var legend = new AmCharts.AmLegend(); chart.addLegend(legend); OR AmCharts.makeChart("chartdiv", { "legend": { "useGraphSettings": true }, } Just remove the above lines from your...

Login Signup PopUp

javascript

In your code you have 2 options to solve it first is jquery and second one is css. 1) Jquery On load trigger click event. $('#cont-1').click(); OR 2) CSS Add hide class in second tab <div class="tabcontent hide" id="cont-2-1"> and add activeLink class for login <a href="javascript:;" class="inactive activeLink" id="cont-1">Login</a>...

submitting form then showing loading image by javascript

javascript,html

Let suppose on button click you are calling ajax method <button onclick="LoadData();"/> before ajax call show image and onComplete ajax method hide this image function LoadData(){ $("#loading-image").show(); $.ajax({ url: yourURL, cache: false, success: function(html){ $("Your div id").append(html); }, complete: function(){ $("#loading-image").hide(); } }); } ...

Converting “i+=n” for-loop to $.each

javascript,jquery

A jQuery only way would be to iterate over the nth-child(4n) $('.thumbnail:nth-child(4n)').each(function(){ $(this) .prevAll('.thumbnail').andSelf() .wrapAll($('<div/>',{class:"new"})) }); Demo Considering the complexity, not sure whether the prevAll() performs better than the plain for loop. Referring one of my similar answer here...

Replacing elements in an HTML file with JSON objects

javascript,json,replace

obj.roles[0] is a object {"name":"with whom"}. you cant replace string with object. you need to refer to property "name" in the object obj.roles[0].name Another problem is that var finalXML get a new value every line. you need to add a new value to the variable, not replcae it. var finalXML...

want to show and hide text using “this” jquery

javascript,jquery

I guess OP wants to link the button more with corresponding click span class $('.clickme').click(function(){ $(this).parent().prev().find(".click").toggle(); }); FIDDLE DEMO...

Saving data using promises

javascript,parse.com,promise

Instead of going for recursive, you can try this: classPromise = array.map(function(obj){ return obj.save();}); in es6, same thing can be: classPromise = array.map(obj => obj.save()); Edit You can reduce the whole function to: function myFunction(array, value) { if ( !array || !array.length) return; console.log("array: " + array.length); if (!value) value...

How to find the days b/w two long date values

javascript,jquery,date

First you need to get your timestamps in to Date() objects, which is simple using the constructor. Then you can use the below function to calculate the difference in days: var date1 = new Date(1433097000000); var date2 = new Date(1434479400000); function daydiff(first, second) { return (second - first) / (1000...

Get all prices with $ from string into an array in Javascript

javascript,regex,currency

It’s quite trivial: RegEx string.match(/\$((?:\d|\,)*\.?\d+)/g) || [] That || [] is for no matches: it gives an empty array rather than null. Matches $99 $.99 $9.99 $9,999 $9,999.99 Explanation / # Start RegEx \$ # $ (dollar sign) ( # Capturing group (this is what you’re looking for) (?: #...

access the json encoded object returned by php in jquery

php,jquery,ajax,json

Try: $.ajax({ url: "functions.php", dataType: "JSON", data: {id: id}, type: 'POST', success: function(json){ for(var i=0;i<json.length;i++){ alert(json[i].fname); } } }); ...

slideToggle state not working with multiple boxes

javascript,jquery,cookies

Use onbeforeunload function of javascript window.onbeforeunload = function() { //Declare cookie to close state } This function will be called every time page refreshes Update: To make loop through every value use this $.each this way: var new_value = ""; window.onbeforeunload = function() { $.each($('div.box_container div.box_handle'),function(index,value){ new_value = ($(value).next('.box').css('display') ==...

Teechart HTML5, line color and thickness

javascript,html5,teechart

Having a Line series: To modify the line thickness, change the series format.stroke.size property. Ie: Chart1.series.items[0].format.stroke.size=2; To modify the series color, change the series format.stroke.fill property. Ie: Chart1.series.items[0].format.stroke.fill="red"; ...

Dynamically resize side-by-side images with different dimensions to the same height

javascript,html,css,image

If it's responsive, use percentage heights and widths: html { height: 100%; width: 100%; } body { height: 100%; width: 100%; margin: 0; padding: 0; } div.container { width: 100%; height: 100%; white-space: nowrap; } div.container img { max-height: 100%; } <div class="container"> <img src="http://i.imgur.com/g0XwGQp.jpg" /> <img src="http://i.imgur.com/sFNj4bs.jpg" /> </div>...

How to remove all the borders of a selectbox?

jquery,html,css,drop-down-menu

Firefox has some problems with select-background. You can try this code - it'll remove the arrow, and then you can add a background image with your arrow (I took an icon from google search, just put you icon instead) I get this on FireFox (You can use any arrow icon...

How to get my node.js mocha test running?

javascript,node.js,mocha,supertest

Create a separate file called app.js. The only purpose of this file would be to run the server. You'll also need to export your app object from server.js. So, your server.js would look like this // set up ====================================================================== var express = require('express'); var app = express(); // create our...

change css dynamically by selecting dropdown list item

jquery,html,css,drop-down-menu

I have created a working example for you. You can find the jsfiddle in here This piece of code uses JQuery. (Remember, for these type of tasks, JQuery is your friend =] ). HTML <select id="dropDownMenu"> <option value="option1" selected="selected">yes</option> <option value="option2">no</option> </select> <br> <img id="picture" src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f5/House_Sparrow_mar08.jpg/220px-House_Sparrow_mar08.jpg"> Javascript function changeStyle(){...

Google map infowindow position

javascript,google-maps,events,infowindow

Two issues: There is a typo in your click listener code, javascript is case sensitive, infowindow and infoWindow are different objects, so you are not setting the position of the infowindow correctly. infowindow.open(map); infoWindow.setPosition(event.latLng); You are currently placing the infowindow at the place that is clicked infoWindow.setPosition(event.latLng);. If you want...

Sockets make no sense?

javascript,node.js,sockets

The client doesn't get to cause arbitrary events to fire on the socket. It is always a message event. Using the same client, try this server code in your connection handler: socket.on('message', function(data) { // data === "pressed", since that's what the client sent console.log("Pressed!"); socket.close(); }); ...

Not able to access variables in required file

javascript,gulp,require,browserify

Without custom logic, it's not possible to achieve what you want. However I believe you could find a compromise by using ES6 modules instead of CommonJS modules. You would be able to write export var test = 'test'; which declares and exports a variable test. You can then import it...

Javascript function to validate contents of an array

javascript,arrays

You can use a simple array based test like var validCodes = ['IT00', 'O144', '6A1L', '4243', 'O3D5', '44SG', 'CE64', '54FS', '4422']; function validItems(items) { for (var i = 0; i < items.length; i++) { if (validCodes.indexOf(items[i]) == -1) { return items[i]; } } return ''; } var items = ["IT00",...

Javscript Replace Text in tags without changing children element HTML and Content

javascript,jquery

The way I think you will have to do it is in each element individually and use this jquery small plugin I rewrite here is the code and also fiddle the html <div id="parent"> thisi sthe fpcd <p>p</p> </div> plugin to find the content of the selector text without child...

Substring of a file

javascript,arrays,substring

To get your desired output, this will do the trick: var file = "a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d"; var array = file.split(", ") // Break up the original string on `", "` .map(function(element, index){ var temp = element.split('|'); return [temp[0], temp[1], index + 1]; }); console.log(array); alert(JSON.stringify(array)); The split converts...

Error: [$injector:unpr] Unknown provider: RestangularProvider <- Restangular <- ctrlAG

javascript,angularjs,restangular

You didn't inject module of 'Restangular' service. Try like this angular.module('AngApp', ['angularGrid','restangular']); ...

Angular $http and Fusion Tables in IE9

javascript,angularjs,internet-explorer-9,google-fusion-tables

You should use the Angular $http.jsonp() request rather than $http.get(). JSONP or “JSON with padding” is the communication technique which allows for data to be requested from a server under a different domain (also known as a Cross Origin Request). Which is what you have used in your jQuery AJAX...

Javascript: Forloop Difference between i++ and (i+1)

javascript,loops,for-loop

The i++ is using post increment, so the value of the expression i++ is what the value was in the variable i before the increment. This code: if(sortedLetters[i] !== sortedLetters[i++]) return true; does the same thing as: if(sortedLetters[i] !== sortedLetters[i]) return true; i = i + 1; As x !==...

Get elements containing text from array

javascript,jquery,html,arrays,contains

You can use :contains selector. I think you meant either one of those values, in that case var arr = ['bat', 'ball']; var selectors = arr.map(function(val) { return ':contains(' + val + ')' }); var $lis = $('ul li').filter(selectors.join()); $lis.css('color', 'red') <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li>cricket bat</li> <li>tennis ball</li> <li>golf ball</li>...

Parsing XML array using Jquery

javascript,jquery,xml,jquery-mobile

EMI and CustomerName are elements under json so you can use .find() to find those elements and then text() to get its value. $(data).find("json").each(function (i, item) { var heures = $(item).find("CustomerName").text(); var nbr = $(item).find("EMI").text(); console.log(heures); }); .attr() is used to get the attribute value of an element like in...

Detect when the jQuery UI slider is being moved?

jquery,html,css,jquery-ui

You can use 3-Events: - Start (Start-Sliding) -> Stop Player - End (End-Sliding) -> Start Player - Slide (Sliding) -> Move Player-Position $("#range").slider({ range: "min", start: function(event, ui) { player.pauseVideo(); }, stop: function(event, ui) { player.playVideo(); }, slide: function(event, ui) { player.seekTo(ui.value,true); return false; } }); Demo: http://codepen.io/anon/pen/EjwMGV...

How to remove unmatched row in html table using jquery

jquery,html

Try this solution: var notrem = []; $('#Table1 tr').each(function(){ var currentRowHTML = $(this).find("td:first").html(); $('#Table2 tr').each(function(i){ var c= $(this).find("td:first").html(); if(c == currentRowHTML ){ notrem.push(i); } }); }); $('#Table2 tr').each(function(i){ if(notrem.indexOf(i) < 0){ $(this).remove(); } }); Explanation: First gather all indexes of Table2 that are equal and are not to be removed....

Can't call fetch directly in Backbone model listenTo

javascript,backbone.js,coffeescript

The handler for each type of event is passed a certain set of arguments. The Catalog of Events has this to say about a "change" event: "change" (model, options) — when a model's attributes have changed. So if you say this: this.listenTo(members, 'change', this.fetch) then fetch will be called like...