Bug in javascript function - javascript

I've got a bug when I'm using a javascript function : my function displays the content of a div element but when I uncomment some code it doesn't work anymore.
Someone has any idea why ?
function traverse(){
var root=document.getElementById('tree0').childNodes;
for(var i=0;i<root.length;i++) {
var lis = root[i];
var number =0;
for (var member in lis) {
output.innerHTML+=lis[member];
/*var assertion = lis[member];
var result = assertion.indexOf("Bookmarks menu");
if(result != -1) {
output.innerHTML+='Test';
}*/
}
}
}
thanks,
Bruno

You may get more that you expect when you do for ... in ...
Is THIS what you want? http://jsfiddle.net/bM9Bn/
<div id="tree0">
<div id="bla">
bla
</div>
<div id="Bookmarks menu">
Bookmarks Menu
</div>
</div>
<hr />
<div id="output"></div>
<script>
var output = document.getElementById("output")
function traverse(){
var root=document.getElementById('tree0').childNodes;
for(var i=0;i<root.length;i++) {
var lis = root[i];
var number =0;
for (var member in lis) {
// output.innerHTML+="["+member+":"+lis[member]+"]";
if (member == "id" || member == "textContent") {
output.innerHTML+="["+member+":"+lis[member]+"]";
var assertion = lis[member];
// the typeof test not needed if we only process textContent and ID
if (typeof assertion == "string") {
var result = assertion.indexOf("Bookmarks menu");
if(result != -1) {
output.innerHTML+='<span style="color:red">Test</span>';
}
}
}
}
}
}
traverse()
</script>

Just looking quickly- var and if statement should both us resultat?
var resultat = assertion.indexOf("Bookmarks menu");
if(result*at* != -1) {

You are checking the 'result' variable, but setting the 'resultat' variable. Try using resultAt in the conditional, and I think it will work for you.

Related

Add space after dot

Good day. I've got some problem.
I've got input where I wrote some information.
Example:
<div class="wizard wizardstep1" ng-controller='someCtrl'>
<p class="wizardtitle">Put you Theme</p>
<input id="taskTheme" required type="text" placeholder="Put you Theme" ng-model="taskThemeWizardInputValue" ng-change="checkThemeWizardInputValue()">
</div>
And I've got my controller.
Example:
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
strt[i] = strt[i].charAt(0).toUpperCase() + strt[i].substr(1);
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
How I can add space after dot? Who knows?
Here is link to jsfiddle with my example.
We achieve it by adding space to each splitted string other than first one and an empty string
function someCtrl($scope) {
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
var addSpace='';
if(i>0 && strt[i].trim().length>0){
addSpace=' ';
}
strt[i] = addSpace+strt[i].trim().charAt(0).toUpperCase() + strt[i].trim().substr(1);
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div class="wizard wizardstep1" ng-controller='someCtrl'>
<p class="wizardtitle">Put you Theme</p>
<input id="taskTheme" required type="text" placeholder="Put you Theme" ng-model="taskThemeWizardInputValue" ng-change="checkThemeWizardInputValue()">
</div>
</div>
You can do this simply by changing strt.join('.') to strt.join('. ').
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
strt[i] = strt[i].trim();
if(strt[i].length > 0) {
strt[i] = ' '+strt[i].charAt(0).toUpperCase() + strt[i].substr(1);
}
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
This is working fiddle
I suggest creating a directive so that you can plugin this behaviour whenever required., rather than writing your ng-change in every controller.
In directive simple line element.val(event.target.value.split(".").join(". ")); will work for you., with help of directive controller parameter.
See example fiddle

Get the implicit lang attribute of an HTML element

Suppose you have an HTML page that contains sections in different languages, like this:
<html lang=en>
<div lang="th">
<p id="test1">ไทย</p>
</div>
<p id="test2">Implicitly English</p>
<div lang="en-CA">
<p id="test3">As Canadian as possible under the circumstances</p>
</div>
<p lang="en-AU"id="test4">Explictly Aussie</p>
</html>
Is there a direct way to discover which particular language code applies to a given HTML element? Something like:
// pseudo-code
var lang = myElement.getLang()
Here's what appears to be a very roundabout solution:
function getLang(element) {
var lang = element.getAttribute("lang")
if (!lang) {
var elements
, languages
, language
, ii
, selector
// Find all elements with an explicit lang attribute
elements = [].slice.call(document.querySelectorAll("*[lang]"))
// Determine which languages are present
languages = []
for (ii in elements) {
lang = elements[ii].getAttribute("lang")
if (languages.indexOf(lang) < 0) {
languages.push(lang)
}
}
lang = "" // reset
for (ii in languages) {
language = languages[ii]
selector = ":lang(" + language + ")"
elements = [].slice.call(document.querySelectorAll(selector))
if (elements.indexOf(element) > -1) {
if (lang.length < language.length) {
lang = language
}
}
}
}
return lang
}
Is there a more obvious way?
jsFiddle
I updated your fiddle with the following code, which you can run in this snippet. This simplifies it greatly.
function getLang(elem) {
var lang = "";
if (elem) {
var elements = [];
var queryResult = document.querySelectorAll("[lang]");
try {
//Wrapping in a try catch block to handle unsupported browsers.
elements = [].slice.call(queryResult);
} catch (error) {
for (var i = 0, len = queryResult.length; i < len; i++) {
elements.push(queryResult[i]);
}
}
if (elements.length > 0) {
//Find in the NodeList where the element is either itself or the first parent with lang attribute of the given element.
var matches = elements.filter(function(e) {
return e === elem || e.contains(elem);
}); //ES2015 -> elements.filter(e => e === elem || e.contains(elem));
var match = matches.length > 0 ? matches[matches.length - 1] : matches[0];
lang = match.lang ? match.lang : lang;
}
}
return lang;
}
var result = getLang(document.querySelector("#test1")) + " ";
result += getLang(document.querySelector("#test2")) + " ";
result += getLang(document.querySelector("#test3")) + " ";
result += getLang(document.querySelector("#test4"));
alert(result);
<body lang=en>
<div lang="th">
<p id="test1">ไทย</p>
</div>
<p id="test2">Implicitly English</p>
<div lang="en-CA">
<p id="test3">As Canadian as possible under the circumstances</p>
</div>
<p lang="en-AU" id="test4">Explictly Aussie</p>
</body>

javascript Bubble sort problems (probably very easy)

<html>
<script>
var tal;
var array = [];
var element=parseIFloat();
function bubbleSort(A){
var swapped,
len = A.length;
if(len === 1) return;
do {
swapped = false;
for(var i=1;i<len;i++) {
if(A[i-1] > A[i]) {
var b = A[i];
A[i] = A[i-1];
A[i-1] = b;
swapped = true;
}
}
}
while(swapped)
}
function insertnumber(){
var element=document.getElementById("element").value;
insert (element,array);
}
function insert(element, array) {
array.push(element);
alert(array);
bubbleSort(array);
alert(array);
}
</script>
<body>
<input type="button" value="Mata in" onclick="insertnumber()" id="resultat">
tal<input type="number" id="element" autofocus>
</body>
</html>
This my code but i really dont know how to get it working again, my problem is that i cant get it to read numbers correctly, trying to use "var element=parseIFloat(); " but that doesnt seem to work..
Thanks :)
Sure, var element=parseIFloat();
was meant to be var element=parseFloat();
and put between
var element=document.getElementById("element").value;
and
insert (element,array);

Show HTML in Console.Log() instead of jQuery selection Object

I'm to output the real html in Chrome developer console for easier debugging.
So I thought of making a chrome extension, which is Chrome Extension.
I copied the real console.log() to console.nativeLog(); and I added my own custom function to console.log();
Here is the code:
<div class="myDiv">
<input type="text" id="inp1" title="title1" />
<input type="text" id="inp2" title="title2" />
<input type="text" id="inp3" title="title3" />
<input type="text" id="inp4" />
<input type="text" id="test" value="">
</div>
<input type="button" id="btn1" value="Add" />
<script type="text/javascript">
console.nativeLog = console.log;
var arr= new Array();
for(var i=0;i<100;i++){
arr[i] = i+','+i;
}
var fav = JSON.parse('[{"href":"/EMS-ILS/Modules/Supplier_Profile/Supplier_Profile.aspx?ModID=6&WebPageID=38","text":"Supplier Profile"},{"href":"/EMS-ILS/Modules/Customer_Profile/Customer_Profile.aspx?ModID=6&WebPageID=57","text":"Customer Profile"},{"href":"/EMS-ILS/Modules/Costing_Profile/Costing_Profile.aspx?ModID=6&WebPageID=50","text":"Costing Profile"}]')
console.log = function (val){
if(typeof(val)=='string'){
console.nativeLog(val);
return;
}
try{
for(var x=0;x<arguments.length;x++){
var arr = arguments[x];
try{
if(!arr.length)
console.nativeLog(arr);
else {
for(var i=0;i<arr.length;i++)
console.nativeLog(arr[i]);
}
}catch(err1){
console.nativeLog(arr);
}
}
}
catch(err2){
console.nativeLog(val);
}
}
$(document).ready(function(){
console.log('-------------');
console.log($('input'));
console.log('-------------');
console.log($('#inp1'));
console.log('-------------');
console.log($('#badId'));
console.log('-------------');
console.log($('input'), $('#bad'), $('input:text'), fav, 0, arr)
});
</script>
Everything works fine, but the last one. If the jquery object contains no results, it will still print the context jquery object.
This is the output in console.
How can prevent that? Any Ideas. Thanks.
Check out this fiddle http://jsfiddle.net/tppiotrowski/KYvDX/3/. This will print each argument on a separate line and print [] if the jQuery object is empty:
console.nativeLog = console.log;
console.log = function(val) {
var x = 0;
for (x; x < arguments.length; x++) {
var item = arguments[x];
// check if we are dealing with jQuery object
if (item instanceof jQuery) {
// jQuery objects with length property are
// the only ones we want to print
if (item.length) {
for (var i = 0; i < item.length; i++) {
console.nativeLog(item[i]);
}
} else {
console.nativeLog('[]');
}
} else {
console.nativeLog(item);
}
}
}
This is a more accurate replication of the actual console.log behavior for printing multiple arguments eg. console.log('a', 'b', 2, []) on one line: http://jsfiddle.net/tppiotrowski/KYvDX/4/
console.nativeLog = console.log;
console.log = function() {
var x = 0;
var output = [];
for (x; x < arguments.length; x++) {
item = arguments[x];
if (item instanceof jQuery) {
if (item.length) {
for (var i = 0; i < item.length; i++) {
output.push(item[i]);
}
} else {
output.push('[]');
}
} else {
output.push(item);
}
}
console.nativeLog.apply(this, output);
}
Try that
console.log($('#badId')[0] != undefined ? $('#badId') : 'do not exist');
http://jsfiddle.net/bkPRg/2/
try
.html()
or
.text()
Also you might check this one for the jquery .length property:
var arr = arguments[x];
try{
if(!arr.length)
Just to add a judgement before print the jQuery object
console.log = function (val){
if(typeof(val)=='string'){
console.nativeLog(val);
return;
}
else if(val instanceof jQuery && val.length==0)
{
console.nativeLog("A jQuery object with no html element");
return;
}

Background change not working in javascript. whats wrong?

I am using jquery slider, i have a single layout and a center div for content..i need to change the color of the layout while i slide on a different page. This is What i am doing using asp.net mvc3.
HTML:
<div id="iPhone_Product">
<div class="slides_containeriphone" >
#if (Model == null)
{
<div class="animateriphone" id="1" title="iphone">
#Html.Partial("`enter code here`_iPhone_Main")
</div>
<div class="animateriphone" id="2" title="salah">
#Html.Partial("Salah")
</div>
<div class="animateriphone" id="3" title="tasbeeh">
#Html.Partial("_Tasbeeh")
</div>
}
else
{
foreach (string s in Model)
{
<div class="animateriphone">
#Html.Partial(s);
</div>
}
}
</div>
</div>
Javascript:
function color_change() {
var ids = new Array();
ids[0] = '1';
ids[1] = '2';
ids[2] = '3';
for (var item = 0; item < ids.length; item++) {
var x = document.getElementById(ids[item]);
}
if (x.id == '1' && x.title=='iphone') {
$(".st_tabs_container").css({ "background-color": "#c8c7c7" });
}
else
if (x.id == '2' && x.title == 'salah') {
$(".st_tabs_container").css({ "background-color": "yellow" });
}
else
if (x.id == '3' && x.title == 'tasbeeh') {
$(".st_tabs_container").css({ "background-color": "#c8c7c7" });
}
}
$(document).ready(function () {
color_change();
});
i have used this javascript to change the background but its not working, any help would be appericiated.
I think the issue is that you are using numbers for ids. Try starting your id values with letters. I think you should consider prefixing your ids, i.e. id1, id2, or something like that.
And you are closing the for loop too early, Nest all your if/else logic inside it as well.
Isn't x always going to be 3 since you are reseting x inside a loop.
You are looping over all your elements without doing anything to them, so depending on what you are trying to do, you might need to move the if-statements into the for-loop as well, or make use of the x in a proper way from within the for-loop.
Not entirely sure what you want to accomplish, but I've put together what I believe you are trying to do: http://jsfiddle.net/ZuzTU/1/
function color_change() {
var ids = new Array(); ids[0] = '1'; ids[1] = '2'; ids[2] = '3';
for (var item = 0; item < ids.length; item++) {
var x = document.getElementById(ids[item]);
if (x.id == '1' && x.title=='iphone') {
$("#" + x.id).css({ "background-color": "#c8c7c7" });
}
else if (x.id == '2' && x.title == 'salah') {
$("#" + x.id).css({ "background-color": "yellow" });
}
else if (x.id == '3' && x.title == 'tasbeeh') {
$("#" + x.id).css({ "background-color": "#c8c7c7" });
}
}
}
$(document).ready(function () {
color_change();
});​
Pretty sure you're not calling the ids right, try this:
<div class="animateriphone" id="id2" title="salah">
var x = document.getElementById('id'+ ids[item]);

Categories

Resources