Phantomjs change object property inside page evaluate - javascript

I'm new to JavaScript and PhantomJS. I'm trying to store links from a webpage and then modify. The problem is that I can't modify my array after page.evaluate.
var player = 0;
var links = page.evaluate(function() {
var a = document.querySelectorAll(".link[rel='nofollow']:not(#bg)");
for(var i =0; i < a.length; i++) {
array.push({
"html":a[i].innerHTML,
"link":a[i].href
}
);
}
return array;
});
//Not setting 1 as a value
links[player]["link"] = 1;
I think that It's happening because I have already set player value when the function is executed, but is there way that I could modify this value?

Your current code replaces a copy of a copy of a reference to the actual data that you want to change. Of course, that cannot work.
If you want to change a property/content on a page, then you need to access the page and change it:
var player = 0;
page.evaluate(function(player) {
var a = document.querySelectorAll(".link[rel='nofollow']:not(#bg)");
a[player].href = "1";
}, player);
I don't think that "1" is an appropriate value for the href value, but it looks like that is what you want to do.

Related

Making variables assigned HTML ids with a function

I can make variables one by one like this:
var bookName = document.getElementById('bookName').value,
author = document.getElementById('author').value,
translator = document.getElementById('translator').value,
pageCount = document.getElementById('pageCount').value,
publisher = document.getElementById('publisher').value,
isbn = document.getElementById('isbn').value,
printingYear = document.getElementById('printingYear').value;
But it's so hard to write and it doesn't fit with the DRY rule. So I changed the code to this:
function variableMaker(argument) {
var tags = document.getElementsByTagName(argument);
for (var i = 0; i < tags.length; i++) {
var tags[i].name = tags[i].value;
}
}
variableMaker(input);
But I can't understand if it is the true way or if it is working? How do I check if it's true or not?
In this code, I tried to get the computer find all the input tags and make variables with their name property and assign it to its values for each of them.
If I understand correctly then you want to gather data from all <input> elements. If so, then you need to call it like this:
variableMaker('input'); // use quotes!
Still even then your function does not return anything, it just ends.
You'd also better create your own object for the return collection, instead of adding values to an existing object.
Here is a working solution:
function variableMaker(tagName) {
var elements = document.getElementsByTagName(tagName);
var items = {};
for (var i = 0; i < elements.length; i++) {
var elem = elements[i];
items[elem.id] = elem.value; // Use id as key, each points to the corresponding value.
}
return items;
}
var values = variableMaker('input');
console.log(values); // show the entire return object
console.log(values.author); // access individual items from the return object
console.log(values.isbn);
<input type="text" id="author" value="Dahl">
<input type="text" id="isbn" value="1234">
.

Show value of variable from json string

I have a for-loop:
var player = 5;
for (var i = 0; i <10; i++) {
$("#id").append('<div class="game_content_text">'+json_var[i].content+'</div>');
}
The json looks like:
"content":"<script>player</script>"
Now I only want to to write down the 5 but nothing is showing...
Edit: I simplified it. Why I have to show more code? The problem is in this lines...
For example if i show a simple text from the json ("content":"example!") it works...
For explanation:
I have a buck of personal questions in the JSON Feed.
Example: "Hello 'name_variable' how are you?"
And in the the 'name_variable' i want show random names...
If we append script tag dynamically then you need to call that code which is inside newly added script.
A script tag result cannot be assign a variable or it cannot be shown as result.
You can try following example
$(function(){
var test = "this.Foo = function() {alert('hi');}";
var F=new Function (test);
(new F()).Foo(); //Shows "Hi" alert
});
I'd like to get more code simply for the fact that I can understand the context better, because your code is rather confusing.
So apparently you try to display the value player in all your appended elements?
var player = 5;
for (var i = 0, l = json_var.length; i < l; i++) {
$("#id").append('<div class="game_content_text">' + player + '</div>');
}
Otherwise, if you really need that script to be stored in the json (for some reason). I'm assuming the class "game_content_text" is only used for this.
var player = 5;
for (var i = 0, l = json_var.length; i < l; i++) {
$("#id").append('<div class="game_content_text">' + json_var[i].content + '</div>');
}
"content": "<script>$('.game_content_text').append(player);</script>"
I'm not all that familiar with jQuery, but that should work.
Also, I really do not recommend this.

How can I dynamically index through datalayer tags in GTM?

I'm using the DuracellTomi datalayer plugin to push cart data from woocommerce to a GTM model to handle some tracking.
The DuracellTomi plugin pushes content to the transactionProducts[] array in the following format:
transactionProducts: Array[1]
0 : Object
category:""
currency:"USD"
id:8
name:"Test"
price:100
quantity:"1"
sku:8
I'd like to loop through this array and unstack it into three separate arrays, pricelist, skulist, and quantitylist. Currently I anticipate doing so as some variation on
//Get Product Information
if(stack = {{transactionProducts}}){
for(i = 0; i < stack.length; i++) {
if(stack.i.sku){
skulisttemp.i = stack.i.sku;
}
if(stack.i.price){
pricelisttemp.i = stack.i.price;
}
if(stack.i.sku){
quantitylisttemp.i = stack.i.quantity;
}
}
{{skulist}} = skulisttemp;
{{pricelist}} = pricelisttemp;
{{quantitylist}} = quantitylisttemp;
}
Obviously this is not going to work because of how the tag referencing is set up, but I'm wondering if anyone has dealt with this and knows what the best way to index through these arrays might be. (For those who don't know, the square bracket array call doesn't work with GTM variables and instead the . format is used instead.)
You would need to create 3 variable type custom javascript function that picks your required value from dataLayer and returns it in an array.
Something like
function(){
var products = {{transactionProducts}};
var skuArray = [];
for(i = 0; i < products.length; i++) {
if(products[i].sku){
skuArray.push(products[i].sku)
}
}
return skuArray
}
hope this helped you :)

Javascript: Traversing through array and accessing its various elements?

Essentially what I'm trying to do right now is, given some input text, I split it up by white space and display on a
div id= "animation"
Every time a button is clicked, the array should go forward one word.
This is my current attempt.
function displayText() {
var displayText = document.getElementbyID("animation");
var list = (document.getElementbyID("input").split(/[ \tn]+/);
for (var i = 0; i < list.length; i++) {
displayText.innerHTML = list.get[i];
}
}
Is my thought process somewhat correct? For whatever reason, it doesn't seem to be working.
there are multiple issues in your method
function displayText() {
var displayTextAnimation = document.getElementbyID("animation"); //keep variable name and method name different
var list = (document.getElementbyID("input").value).split(/[ \tn]+/); //use value property and observe extra bracket
for (var i = 0; i < list.length; i++) {
displayTextAnimation.innerHTML = list.charAt(i); //observe replacing get by charAt
}
}

Javascript Dynamic GetElementByID

I would like to use the same function on two different elements without duplicating my code and changing the id. I'd like to pass the ID as a parameter into my function but it's not working.
function getSelected(id){
var selected = new Array();
**var selObj = document.getElementById(id);** //The problem is here
var count = 0;
for (x=0; x<selObj.options.length; x++){
if (selObj.options[x].selected){
selected[count] = selObj.options.value;
count++;
}
}
alert(count)
}
Any ideas?
Looks to me as if the error is somewhere else, specificially in this line:
selected[count] = selObj.options.value;
Shouldn't that be:
selected[count] = selObj.options[x].value;
or (without the need for an extra "count" variable)
selected.push( selObj.options[x].value );
(Furthermore, you're missing a var in front of x = 0, thus making x a global variable.)

Categories

Resources