console.log of undefined doesn't log - javascript

I am trying to fetch data from www.matchbook.com using this script
function scrape(){
var row = document.querySelectorAll(".mb-runner")[0]; //get rows
console.log(row.textContent); //log row content
}setInterval(scrape, 1000);
This code produces inline data ArsenalArsenal1.347$2591.349$20,8171.352$4811.363$11,2331.368$11,4571.379$9,948 without delimiter. Do you know how should I separate this data?
Here I am posting screen how data looks on a web

When the contents of that cell changes to MAKE OFFER, it no longer has the mb-price__odds class, so the selector matches the next cell.
Instead of selecting by this cell's class, use the class of the container, which I don't think goes away.
Then check whether this matched anything before trying to access .textContents.
function scrape() {
var cell = document.querySelector(".mb-price:first-of-type .mb-price__odds");
if (!cell) {
console.log("Log me null please, do not skip to another cell !");
} else {
console.log(cell.textContents);
}
}

Finally I solved my problem via this javascript code:
function scrape(){
var radek = document.querySelectorAll(".mb-runner")[2];//row
var bunka = radek.querySelectorAll(".mb-price")[0]; //cell
console.log(bunka.textContent); //cell value
}setInterval(scrape, 1000); //run every second

Try this.
No need to querySelectorAll if you only need the first element
Find the parent first and look for the price only if the element exists
Put null check on the element && the text content
function scrape(){
var x = document.querySelector(".mb-price");
var y = x && x.querySelector('.mb-price__odds');
if (y && y.textContent){
console.log(y.textContent);
}
else {
console.log('No Content');
}
}

Related

How to correctly retrieve and change the text's value stored from an array in jQuery?

I'm trying to change each <th> tag with the string values stored in an array. If it reaches the end of the array length, it'll just reset the counter which I already have implemented. I want to be able to keep looping and changing each of the header text values until the end of the table. I've tried several code attempts to be able to change and output the header text below (but none worked; no console error outputs either):
$(this).text() == headerTitleArr[headerIndex];
//$(this).text(headerTitleArr[headerIndex])[thIndex];
//$(this).css("content", headerTitleArr[headerIndex]);
I debugged the code to see what both values were returning and both of them return string values but for some reason, the values from the array headerTitleArr[headerIndex] are not being passed over to $(this).text() which is suppose to be the DOM selector of tr.table tr > th and thus remains the same as you see in console.log output.
Here's my jsfiddle of the issue.
Code Snippet:
if (window.matchMedia('(max-width: 2799px)').matches) {
// do functionality on screens smaller than 2799px
var headerTitleArr = ["Players","Stamina","Home Runs"];
var headerTitleArrLength = 2;
var mainChart = $("#chart1");
var headerIndexCount = 0;
// loop thru each of the tr.table-tr rows tracked by index and change the th text's index with the header text value
$("#chart1 tr.table-tr > th").each(function(thIndex) {
headerIndex = headerIndexCount;
// TO FIX
$(this).text() == headerTitleArr[headerIndex];
//$(this).text(headerTitleArr[headerIndex])[thIndex];
//$(this).css("content", headerTitleArr[headerIndex]);
headerIndexCount++;
// if headerIndex equals to the length of the array, reset value
if (headerIndex == headerTitleArrLength) {
headerIndexCount = 0; // reset value
}
});
}
I think it is here:
Change
$(this).text() == headerTitleArr[headerIndex];
to
$(this).text(headerTitleArr[headerIndex]);

How to check if html if any html element contains text from some Object

I have some object with label and value. Those elements holds some data.
For now i want to loop on html elements and check, what element match this elements. Object is called ui.
Right now i want to select all elements that contains text from any of object elements.
Those elements have class .img.
Below simple javascript:
$("#project").autocomplete({
source: Items,
appendTo: ".autocomplete",
minLength: 2,
response: function (event, ui) {
if (ui.content.length == 0) {
return false;
}
var content = ui.content[0].label;
$.each($('.img'), function () {
if ($(this).is(':contains(' + content + ')')) {
return;
} else {
$(this).fadeOut(100);
}
});
}
});
This code acts as autocomplete, and i want to hide all emelents that don't match data from ui object.
This code works for me almost fine, but there is one thing that break things:
var content = ui.content[0].label;
This selects only first item from object, and i'm looking for a way, how to check all items from obejct to check if text contains data, not only from first obejct element [0].
Thanks for advice.
I create a jsfiddle for you, If I understand the problem
var matchLabelString=_.reduce(ui,function(accumulateString,current){
if(accumulateString == ""){
return current.label;
}
return accumulateString + "|"+current.label;
},"")
var regex = new RegExp("^"+matchLabelString);
$.each($('.img'), function () {
if (regex.test($(this).text())) {
return;
} else {
$(this).fadeOut(100);
}
});
https://jsfiddle.net/3o1oy5y2/
EDIT: I see your code, and I think that my code work anyway. Try it, as you can see I have used underscore library to create a string seperatad by | from array
You can add a loop in your $each callback :
$.each($('.img'), function() {
for (var i = 0; i < ui.content.length; i++) {
var content = ui.content[i].label;
...
}
});
EDIT: Change let to var

What does unescape() function returns?

I have to use unescape() function in an if-else statement. In my website I have two pages, one with a form that the user fills and the second page have to get the information from the filled form by unescape function. I need the if-else statement because in the form I put two radio buttons that each one adds different text areas with different ids' and names so I want to check in the second page what text fields are are filled. (all the fields created by clicking on a radio button which starts a javascript function so in the next page I must check if the field was created and not just to check if it is an unfilled text field).
It is a little bit hard for me to explain so just check the code. In the code you will see params["placeName"] and so on, so placeName for example like all the others is a text field name from the previous page.
So the question is - what does unescape function returns if the component name I insert as a paramater does exist in the previous page?
<script type="text/javascript">
function getParams() {
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx + 1, document.URL.length).split('&');
for (var i = 0; i < pairs.length; i++) {
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
//from here it is what I want to do (I don't know if this condition in the if statement is correct, this is what I ask)
// if (unescape(params["placeName"]) == false) {
// }
// else {
var place = unescape(params["placeName"]);
var country = unescape(params["country"]);
var city = unescape(params["city"]);
var address = unescape(params["address"]);
var type = unescape(params["type"]);
var rate = unescape(params["rate"]);
// }
</script>
It can also work if I could check what radio button is checked
You are asking what will unescape(params["something"]) return if params["something"] is not present. The answer is undefined. So you need to check equivalence to "undefined". Meaning: if (unescape(params["placeName"]) == "undefined") (in this case params["placeName"] is not present (was not created).
The undecode function returns -as it's name indicated- a decoded string. If you enter a value that's not defined it will probably cause an error because of the indefinition. If what you want is to check whether the element was or not created or not you could use
if (params.placeName !== undefined) {
// It was created
}
instead.
Aditionally, if you want to check which radio button was checked use
if (document.getElementById('foo').checked) {
// Radio button with id 'foo' was checked
} else if (document.getElementById('bar').checked) {
// Radio button with id 'bar' was checked
} else if
...

how to check if a checkbox exists

The check box's exist for each row. the table is created by PHP and I need a way to check if the check box exists. when they are created they are given the ID of checkbox_(an incrementing number).
This is what I have so far, but it does not work on checking if the element exists.
var check = true;
var todelete = "";
var counter = 0;
//check if box exisits and record id and post
while(check)
{
if ($("#Checkbox_"+counter).length > 0)
{
todelete = todelete + $("#Checkbox_"+counter).value;
counter = counter + 1;
}
else
{
check = false;
}
}
I have also tried
if ($("Checkbox_"+counter))
if (document.getElementById("tbody").value == null)
Update:
Even with the # symbol or if i do it by javascripts element ID - when I debug the DOM, it hits the while, then the if, adds the value to todelete, adds 1 to the counter, then it goes back to the while, then hits the if
Then bounces back up to the while without even going into the if or the else???
this I do not understand, then it just bounces up and down between the two lines and crash's the browser?
Update2:
I needed to .tostring() the counter when adding it to the string for an element id. problem solved
You can use
if ($("#Checkbox_"+counter).length > 0)
I'm assuming that 'Checkbox_0' is an ID, so I've added the # symbol. If it's the name of the checkbox, you can use
if ($("input[name='Checkbox_"+counter+"']").length > 0);
[edit]Also, you should check to make sure you do / don't need the capital 'C'.
You can use for "checkbox exists in this case"
if ($("#Checkbox_"+counter).length > 0) {
//checkbox exists
}
if (($("#Checkbox_"+counter).length) > 0) {
...
//Or something more generalized
jQuery.fn.exists = function(){
return jQuery(this).length>0;
}
//then, if you have valid selector
if ($("#Checkbox_"+counter).exists()){
//do something here if our selected element exists
}
// if document.getElementById(name) do not exist
// document.getElementById(name).value generate already an error
if (document.getElementById(name) != null) {
// you code if checkbox exist
}

nextSibling issue, should be simple

Ok, I'm trying to come to grips with this nextSibling function in JS. Here's my issue within the following code...
var fromRow = document.getElementById("row_1");
while(fromRow.nodeType == 1 && fromRow.nextSibling != null)
{
var fRowId = fromRow.id;
if (!fRowId) continue;
// THIS ONLY gets done once and alerts "row_1" ONLY :(
alert(fRowId);
fromRow = fromRow.nextSibling;
}
Ok can someone please tell me what is wrong with this code? There are siblings next to this document.getElementById("row_1"); element for sure as I can see them, and they all have id attributes, so why is it not getting the id attributes of the siblings?? I don't get it.
row_1 is a TR element, and I need to get the TR elements next to it within this table, but for some reason, it only gets the 1 element that I can already get using document.getElementById, arggg.
Thanks guys :)
Try:
var fromRow = document.getElementById("row_1");
while(fromRow !== null)
{
var fRowId = fromRow.id;
if (!fRowId || fromRow.nodeType != 1) {
fromRow = fromRow.nextSibling;
continue;
}
// THIS ONLY gets done once and alerts "row_1" ONLY :(
alert(fRowId);
fromRow = fromRow.nextSibling;
}
While fromRow.nextSibling != null would halt on the second to last iteration because you already set fromRow to its nextSibling at the end. Also, you don't necessarily want to halt if the next node isn't an element, you just want to move onto the next one if possible. Finally, if you hit the continue in your original example, you'll run into an endless loop because fromRow would never change value.
Your while loop stops as soon as it encounters a node not of type 1. So if there is any whitespace between your elements the while loop will break after the first element.
What you probably want is:
while(fromRow.nextSibling != null)
{
if(fromRow.nodeType == 1) {
...
}
}

Categories