How Display The Data on Page Load - javascript
I've been working on the Search CRUD using Google WebApp Script via watching a YouTube tutorial, I'm almost done but I'm stuck in a place I couldn't figure out to sort the issue.
I want to load the search field and the data on first page load. but based on this code I need to click on the Search Tab and then get the search field to find the data. How do I get rid of the Search Tab and get straight into the search bar and data.
On Page load
Second Occurrence (After the Click)
My code
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<style>
.nav-link {
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<ul class="nav nav-tabs">
<li class="nav-item">
<div class="nav-link"id="search-link">Search</div>
</li>
</ul>
<div id="app"></div>
<!-- Content here -->
</div>
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script>
var data;
function loadView(options){
var id = typeof options.id === "undefined" ? "app" : options.id;
var cb = typeof options.callback === "undefined" ? function(){} : options.callback;
google.script.run.withSuccessHandler(function(html){
document.getElementById("app").innerHTML = html;
typeof options.params === "undefined" ? cb() : cb(options.params);
})[options.func]();
}
function setDataForSearch(){
google.script.run.withSuccessHandler(function(dataReturned){
data = dataReturned.slice();
}).getDataForSearch();
}
function search(){
var searchinput = document.getElementById("searchinput").value.toString().toLowerCase().trim();
var searchWords = searchinput.split(/\s+/);
var searchColumns = [0,1,2,3,4,5,6,7];
// and or
var resultsArray = data.filter(function(r){
return searchWords.every(function(word){
return searchColumns.some(function(colIndex){
return r[colIndex].toString().toLowerCase().indexOf(word) !== -1
});
});
});
var searchResultsBox = document.getElementById("searchResults");
var templateBox = document.getElementById("rowTemplate");
var template = templateBox.content;
searchResultsBox.innerHTML = "";
resultsArray.forEach(function(r){
var tr = template.cloneNode(true);
var hinmokuColumn = tr.querySelector(".hinmoku");
var buhinCodeuColumn = tr.querySelector(".buhinCode");
var buhinNameColumn = tr.querySelector(".buhinName");
var hitsuyoColumn = tr.querySelector(".hitsuyo");
var genkaColumn = tr.querySelector(".genka");
var kobaiColumn = tr.querySelector(".kobai");
var sagakuColumn = tr.querySelector(".sagaku");
var kenshoColumn = tr.querySelector(".kensho");
hinmokuColumn.textContent = r[0];
buhinCodeuColumn.textContent = r[1];
buhinNameColumn.textContent = r[2];
hitsuyoColumn.textContent = r[3];
genkaColumn.textContent = r[4];
kobaiColumn.textContent = r[5];
sagakuColumn.textContent = r[6];
kenshoColumn.textContent = r[7];
searchResultsBox.appendChild(tr);
});
}
function loadSearchView(){
loadView({func:"loadSearchView", callback: setDataForSearch});
}
document.getElementById("search-link").addEventListener("click",loadSearchView);
function inputEventHandler(e){
if (e.target.matches("#searchinput")){
search();
}
}
document.getElementById("app").addEventListener("input",inputEventHandler);
</script>
</body>
</html>
Server Side Code
function getDataForSearch(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("Array");
return ws.getRange(2, 1, ws.getLastRow(),8).getValues();
}
I need to type letters in order to data display.
Screen Shot 3
Issue:
There are some actions that are currently happening when the Search tab is clicked.
You want these actions to happen when the page loads.
Solution:
In the HTML you provided, there's a click event listener attached to the Search tab you mention (id="search-link"):
document.getElementById("search-link").addEventListener("click",loadSearchView);
This means the function loadSearchView is gonna execute when the Search tab is clicked.
If I understand you correctly, you want loadSearchView to execute when the page loads. In that case, you could just add the following event listener:
window.addEventListener("load", loadSearchView);
Notes:
Since you didn't provide server-side code, I cannot know whether loadSearchView will do what you intend it to do. This solution just makes sure loadSearchView is executed when the page loads.
If you want to get rid of the Search tab, just remove it from your HTML (<div class="nav-link"id="search-link">Search</div> and its container elements).
Reference:
Window: load event
Related
Captain.speak() method issue
I am currently learning about objects within class. I created an object with constructor notation in Javascript, and instantiated four different objects with distinct names. For some reason, when I try to run the Captain.speak() method in my code, it doesn't work. It should display the Captain.strPhase string that I created right before initiating the command for the function. When I check this in online compilers, there are no errors, but it doesn't output my string. Would anyone happen to know why? $(document).ready(function() { function Pirate(rank, phrase, id) { output = ""; randNum = 1; secretNum = 1; this.strRank = rank; this.intNum = favnum; this.strPhrase = phrase; this.elOutput = document.getElementById(id); this.speak = function() { this.elOutput.innerHTML += "<br>" + this.strPhrase; }; //End speak this.chooseRandNum = function() { this.randNum = Math.floor(Math.random() * 10); }; //End chooseRandNum }; //End Pirate var Captain = new Pirate("Captain", "", "captain"); var firstMate = new Pirate("First Mate", "I love guessing games!", "pirate1"); var Quartermaster = new Pirate("Quartermaster", "This game should be fun.", "pirate2"); var Gunner = new Pirate("Gunner", "Let's start playing!", "pirate3"); Captain.strPhrase = "Argh maties, ready to play a guessing game?"; Captain.speak(); }); // end of $(document).ready() <html lang="en"> <head> <meta charset="utf-8"> <!-- Begin every html page with everything up to this point (just use your own header block) --> <!-- Also, feel free to remove all the instructional comments as you modify this file to make it yours. --> <!-- This <title> displays in the page tab --> <title>Randomness</title> <!-- This will link to your CSS stylesheet for formatting as soon as you create the file. The page will work without it, though. --> <link rel="stylesheet" href="css/myFancyStylesheet.css"> <!-- This links to the jQuery library so your js code will work Always include this *before* your own js code (extremely important) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- This links to the js code specific for this page --> <script src="Randomness.js"></script> </head> <body> Captain's Guessing Game: <br></br> <div id="captain"> </div> <br></br> <div id="pirate1"> </div> <br></br> <div id="pirate2"> </div> <br></br> <div id="pirate3"> </div> </body> </html>
When I run your code, I get an error message: Uncaught ReferenceError: favnum is not defined If you comment out this line... // this.intNum = favnum; ...everything should work just fine.
I am not sure I can access the second html file using one js file, html element is showing as null when it is a button
I have 2 html files connected to one js file. When I try to access a html element in the second html file using js it doesn't work saying that is is null. I did let elementname = document.getElementById("element") for a element in the second html page then console.log(elementname) and it says it is null. When I do it for a element in the first html page it says HTMLButtonElement {} Here is the html for the first Page <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Not Quuuuiiiizzzz</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>Not Quuuuiiiizzzz</h1> <h2>Join a quiz</h2> <!--Buttons --> <div style="text-align: center;"> <button id="btnforquiz1" onclick="gotoquiz()"></button> <button id="btnforquiz2" onclick="gotoquiz1()"></button> <button id="btnforquiz3" onclick="gotoquiz2()"></button> </div> <h2 id="h2">Create a Quuuuiiiizzzz</h2> <script src="script.js"></script> </body> </html> For the second page <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Not Quuuuiiiizzzz</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body onload="quizLoad()"> <h1 id="question">Hello</h1> <button id="answer1"></button> <button id="answer2"></button> <button id="answer3"></button> <button id="answer4"></button> <script src="script.js"></script> </body> </html> And Finally for the js file : //setting global variables let btn1 = document.getElementById("btnforquiz1") //getting button with id of btnforquiz1 repeat below correct = 0 let btn2 = document.getElementById("btnforquiz2") let btn3 = document.getElementById("btnforquiz3") let question = document.getElementById("question") let answer1 = document.getElementById("answer1") let answer2 = document.getElementById("answer2") let answer3 = document.getElementById("answer3") let answer4 = document.getElementById("answer4") quizNameRel = -1; cosnole.log(question) console.log(answer1) //Quiz Data Quiz_1 = { "What is the capital of buffalo":["Idk", "Yes", "No",0], "What is the smell of poop": ["Stinky"] }; Quiz_2 = [ "What is wrong with you" ]; Quiz_3 = [ "What is wrong with you #2" ] let quiz = { name: ["History Test", "Math Practice", "ELA Practice"], mappingtoans: [0,1,2], QA: [Quiz_1, Quiz_2, Quiz_3] } //quiz data //when body loades run showQuizzs function document.body.onload = showQuizzs() function showQuizzs() { //loops throo the vals seeting the text for the btns for (let i = 0; i < quiz.name.length; i++) { btn1.textContent = quiz.name[i-2] btn2.textContent = quiz.name[i-1] btn3.textContent = quiz.name[i] } } //leads to the showQuizzs function gotoquiz() { location.href = "quiz.html" quizNameRel = quiz.name[0]//I was trying to create a relation so we could knoe which quiz they wnt to do startQuiz() } function gotoquiz1() { location.href = "quiz.html" quizNameRel = quiz.name[1] startQuiz() } function gotoquiz2() { location.href = "quiz.html"; quizNameRel = quiz.name[2]; startQuiz(); } function answerselect(elements){ whichone = Number(elements.id.slice(-2,-1)) if(Quiz_1[whichone]==Quiz_1[-1]){ correct+=1; NextQuestion(); }else{ wrong+=1; } } //gets the keys and puts it into an array function getkeys(dictionary){ tempdict = []; for(i in dictionary){ tempdict.push(i); } return tempdict; } function setQuestion() { let tempdict = getkeys(Quiz_1) console.log(tempdict, getkeys(Quiz_1)); //question.innerHTML = tempdict; } // startQuiz function startQuiz() { switch (quizNameRel){ case quiz.name[0]: //case here setQuestion() break case quiz.name[1]: //case here break case quiz.name[2]: //case here break } } //TO DO: // Set the question // Set the answer // Check if correct button
This is happening because at a time you have rendered only one html file. For example if you render index1.html(first file) then your js will look for rendered element from first file only but here index2.html(second file) is not rendered so your js script is unable to find elements of that file that's the reason it shows null. If you try to render now index2.html rather than index1.html then you will find now elements from index2.html are detected by js script but elements from index1.html are null now.
How to load javascript files using event listeners
This question is not duplicate of Conditionally load JavaScript file and nor this How to include an external javascript file conditionally? I have gone through them, they are kind of similar to what I want to do but not exactly same. Here is how, in the above question the user just wants to load the script file once based on a condition. But in my case I want to load different js files based on click events. So here in my case I have an HTML document: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Experiment</title> <link href="s.css" rel="stylesheet" type="text/css"> </head> <body> <div class="navigation"> <nav> <ul> <li id="home_btn"> Home</li> <li id="about_btn"> About </li> </ul> </nav> </div> <canvas id="myCanvas"> </canvas> <div class="notePane"> <p> This is just a bunch of text not explanation</p> </div> </body> <script src="./exp.js" type="text/javascript"></script> </html> and this h.html file is linked to an exp.js file. Now in the exp.js file : var h_btn = document.getElementById("home_btn"); var a_btn = document.getElementById("about_btn"); var head = document.getElementsByTagName("head")[0]; var js = document.createElement("script"); js.type="module"; h_btn.addEventListener("click", showHome ); a_btn.addEventListener("click", showAbout); function showHome() { js.src="./j1.js"; head.appendChild(js); } function showAbout() { js.src="./j2.js"; head.appendChild(js); } So things work fine when I click the h_btn on the web page. It loads j1.js. But then when I click on the a_btn on the web page I expect to see j2.js linked but I don't see it. I have to refresh the page and then click on a_btn to see j2.js linked. How do I link j1.js and j2.js such that I don't have to refresh the page again and again to load the correct script.
Update: OP has updated the question requirements such that he wants to "unload" a JS file when another is clicked. There is no way to undo all the runtime logic once a JS file is loaded: the only way is to reload the page. Removing the <script> tag or changing the src attribute will not magically unbind event listeners or "undeclare" variables. Therefore, if OP wants to "start anew", the only way is to check if a custom script has been loaded before: if it has, we force reload the page. There are of course many ways to "inform" the next page which source to load, if available: in the example below, we use query strings: var h_btn = document.getElementById("home_btn"); var a_btn = document.getElementById("about_btn"); var head = document.getElementsByTagName("head")[0]; var appendedScriptKey; var scripts = { 'home': './j1.js', 'about': './j2.js' } h_btn.addEventListener("click", showHome); a_btn.addEventListener("click", showAbout); // Check query string if a specific script is set var params = (new URL(document.location)).searchParams; var scriptKey = params.get('scriptKey'); if (scriptKey && scriptKey in scripts) { appendScript(scriptKey); } function appendScript(key) { if (hasAppendedScript) { location.href = location.href + (location.search ? '?' : '&') + 'script=' + key; location.reload(); } var js = document.createElement("script"); js.type="module"; js.src = scripts[key]; head.appendChild(js); appendedScript = key; } function showHome() { appendedScriptKey('home'); } function showAbout() { appendScript('about'); } This is because of how Node.appendChild() works. The first click works because you're creating a new element and inserting it into your document. However, the second click will not work as you've expected because the node already exists: The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position This means that the second click will only mutate the src attribute of the already-injected <script> element instead of creating a new one, and that also means that the second script src will not be loaded. A solution will be to use a function that will create a script tag every single time: var h_btn = document.getElementById("home_btn"); var a_btn = document.getElementById("about_btn"); var head = document.getElementsByTagName("head")[0]; h_btn.addEventListener("click", showHome); a_btn.addEventListener("click", showAbout); function insertScript(src) { var js = document.createElement("script"); js.type = "module"; js.src = src; head.appendChild(js); } function showHome() { insertScript('./j1.js'); } function showAbout() { insertScript('./j2.js'); } But this will also mean that multiple clicks on the same button will cause the script to be injected multiple times. This does not affect browser performance much since the browser has the loaded script cached somewhere, but to guard against this, it might be a good idea to implement some kind of unique identifier per script, and check against that before injection. There are many ways to do this, and this is just one way: var h_btn = document.getElementById("home_btn"); var a_btn = document.getElementById("about_btn"); var head = document.getElementsByTagName("head")[0]; h_btn.addEventListener("click", showHome); a_btn.addEventListener("click", showAbout); // Store scripts that you've injected var scripts = []; function insertScript(src) { // If we have previously attempted injection, then do nothing if (scripts.indexOf(src) !== -1) { return; } var js = document.createElement("script"); js.type = "module"; js.src = src; head.appendChild(js); // Push script to array scripts.push(src); } function showHome() { insertScript('./j1.js'); } function showAbout() { insertScript('./j2.js'); } Alternative unique script injection strategies and ideas: Use ES6 Map() to track unique script sources being injected Perhaps only store src to array/dict/map when the script has successfully loaded
You have to create the element twice, as there can only be one element with 1 src. var h_btn = document.getElementById("home_btn"); var a_btn = document.getElementById("about_btn"); var js1 = document.createElement("script"); var js2 = document.createElement("script"); h_btn.addEventListener("click", showHome); a_btn.addEventListener("click", showAbout); function showHome() { js1.src = "j1.js"; document.body.appendChild(js1); } function showAbout() { js2.src = "j2.js"; document.body.appendChild(js2); } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Experiment</title> <link href="s.css" rel="stylesheet" type="text/css"> </head> <body> <div class="navigation"> <nav> <ul> <li id="home_btn"> Home</li> <li id="about_btn"> About </li> </ul> </nav> </div> <canvas id="myCanvas"> </canvas> <div class="notePane"> <p> This is just a bunch of text not explanation</p> </div> </body> <script src="exp.js" type="text/javascript"></script> </html>
Selenium: Get code source of innerHTML that doesn't show in 'inspect element'
Good day! I have been looking around the whole internet and I didn't find any problem like mine. I'm trying to get data using selenium from 'https://mobile.bet9ja.com/mobile' I have navigated to the path I needed step by step, till I got to the page I wanted. That page loads a picture, then after some time numbers and data that I'm looking for. My full code is: import requests from bs4 import BeautifulSoup import lxml from selenium import webdriver import selenium from selenium.webdriver.common.keys import Keys import time from selenium.webdriver import ActionChains log_in_url = 'https://mobile.bet9ja.com/mobile/login' driver = webdriver.Chrome('/Users/macbook/Downloads/chromedriver') driver.get(log_in_url) user_name = driver.find_element_by_css_selector("input.form-input[type='text']") password = driver.find_element_by_css_selector("input.form-input[type='password']") log_in_button = driver.find_element_by_tag_name('button') user_name.clear() password.clear() # It needs log in user_name.send_keys('user_name') password.send_keys('password') log_in_button.click() time.sleep(5) try: # Close a pop up window close_pop_up_window = driver.find_element_by_class_name('modal-close') close_pop_up_window.click() except: pass time.sleep(2) league_button = driver.find_element_by_id('iconslider_1549_league_element') league_button.click() time.sleep(6) premiere_legue = driver.find_element_by_class_name('col-xs-6') premiere_legue.click() time.sleep(15) after that I have tried all these codes and they return the same result: html = driver.page_source() and html = driver.execute_script("return document.body.innerHTML") and html = driver.execute_script("return document.getElementsByTagName('html')[0].innerHTML") The result is: <html><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"><script type="text/javascript" src="https://bam.nr-data.net/1/c95cd51526?a=214311961&v=1167.2a4546b&to=ZlBXZxcAVkEHV0NbDV8aYEEMTlpXEg1dU09cWldaCQQXXglTXlxNWFtRVh1PSFoW&rst=363&ref=https://vsmobile.bet9ja.com/bet9ja-mobile/login/&ap=5&be=322&fe=360&dc=355&perf=%7B%22timing%22:%7B%22of%22:1588686621313,%22n%22:0,%22u%22:310,%22ue%22:310,%22f%22:4,%22dn%22:5,%22dne%22:5,%22c%22:5,%22s%22:95,%22ce%22:187,%22rq%22:187,%22rp%22:301,%22rpe%22:305,%22dl%22:313,%22di%22:355,%22ds%22:355,%22de%22:359,%22dc%22:360,%22l%22:360,%22le%22:361%7D,%22navigation%22:%7B%7D%7D&fp=360&at=ShdUEV8aRU8%3D&jsonp=NREUM.setToken"></script><script src="https://js-agent.newrelic.com/nr-1167.min.js"></script><script type="text/javascript">(window.NREUM||(NREUM={})).loader_config={licenseKey:"c95cd51526",applicationID:"214311961"};window.NREUM||(NREUM={}),__nr_require=function(e,n,t){function r(t){if(!n[t]){var i=n[t]={exports:{}};e[t][0].call(i.exports,function(n){var i=e[t][1][n];return r(i||n)},i,i.exports)}return n[t].exports}if("function"==typeof __nr_require)return __nr_require;for(var i=0;i<t.length;i++)r(t[i]);return r}({1:[function(e,n,t){function r(){}function i(e,n,t){return function(){return o(e,[u.now()].concat(f(arguments)),n?null:this,t),n?void 0:this}}var o=e("handle"),a=e(4),f=e(5),c=e("ee").get("tracer"),u=e("loader"),s=NREUM;"undefined"==typeof window.newrelic&&(newrelic=s);var p=["setPageViewName","setCustomAttribute","setErrorHandler","finished","addToTrace","inlineHit","addRelease"],l="api-",d=l+"ixn-";a(p,function(e,n){s[n]=i(l+n,!0,"api")}),s.addPageAction=i(l+"addPageAction",!0),s.setCurrentRouteName=i(l+"routeName",!0),n.exports=newrelic,s.interaction=function(){return(new r).get()};var m=r.prototype={createTracer:function(e,n){var t={},r=this,i="function"==typeof n;return o(d+"tracer",[u.now(),e,t],r),function(){if(c.emit((i?"":"no-")+"fn-start",[u.now(),r,i],t),i)try{return n.apply(this,arguments)}catch(e){throw c.emit("fn-err",[arguments,this,e],t),e}finally{c.emit("fn-end",[u.now()],t)}}}};a("actionText,setName,setAttribute,save,ignore,onEnd,getContext,end,get".split(","),function(e,n){m[n]=i(d+n)}),newrelic.noticeError=function(e,n){"string"==typeof e&&(e=new Error(e)),o("err",[e,u.now(),!1,n])}},{}],2:[function(e,n,t){function r(e,n){var t=e.getEntries();t.forEach(function(e){"first-paint"===e.name?c("timing",["fp",Math.floor(e.startTime)]):"first-contentful-paint"===e.name&&c("timing",["fcp",Math.floor(e.startTime)])})}function i(e,n){var t=e.getEntries();t.length>0&&c("lcp",[t[t.length-1]])}function o(e){if(e instanceof s&&!l){var n,t=Math.round(e.timeStamp);n=t>1e12?Date.now()-t:u.now()-t,l=!0,c("timing",["fi",t,{type:e.type,fid:n}])}}if(!("init"in NREUM&&"page_view_timing"in NREUM.init&&"enabled"in NREUM.init.page_view_timing&&NREUM.init.page_view_timing.enabled===!1)){var a,f,c=e("handle"),u=e("loader"),s=NREUM.o.EV;if("PerformanceObserver"in window&&"function"==typeof window.PerformanceObserver){a=new PerformanceObserver(r),f=new PerformanceObserver(i);try{a.observe({entryTypes:["paint"]}),f.observe({entryTypes:["largest-contentful-paint"]})}catch(p){}}if("addEventListener"in document){var l=!1,d=["click","keydown","mousedown","pointerdown","touchstart"];d.forEach(function(e){document.addEventListener(e,o,!1)})}}},{}],3:[function(e,n,t){function r(e,n){if(!i)return!1;if(e!==i)return!1;if(!n)return!0;if(!o)return!1;for(var t=o.split("."),r=n.split("."),a=0;a<r.length;a++)if(r[a]!==t[a])return!1;return!0}var i=null,o=null,a=/Version\/(\S+)\s+Safari/;if(navigator.userAgent){var f=navigator.userAgent,c=f.match(a);c&&f.indexOf("Chrome")===-1&&f.indexOf("Chromium")===-1&&(i="Safari",o=c[1])}n.exports={agent:i,version:o,match:r}},{}],4:[function(e,n,t){function r(e,n){var t=[],r="",o=0;for(r in e)i.call(e,r)&&(t[o]=n(r,e[r]),o+=1);return t}var i=Object.prototype.hasOwnProperty;n.exports=r},{}],5:[function(e,n,t){function r(e,n,t){n||(n=0),"undefined"==typeof t&&(t=e?e.length:0);for(var r=-1,i=t-n||0,o=Array(i<0?0:i);++r<i;)o[r]=e[n+r];return o}n.exports=r},{}],6:[function(e,n,t){n.exports={exists:"undefined"!=typeof window.performance&&window.performance.timing&&"undefined"!=typeof window.performance.timing.navigationStart}},{}],ee:[function(e,n,t){function r(){}function i(e){function n(e){return e&&e instanceof r?e:e?c(e,f,o):o()}function t(t,r,i,o){if(!l.aborted||o){e&&e(t,r,i);for(var a=n(i),f=v(t),c=f.length,u=0;u<c;u++)f[u].apply(a,r);var p=s[y[t]];return p&&p.push([b,t,r,a]),a}}function d(e,n){h[e]=v(e).concat(n)}function m(e,n){var t=h[e];if(t)for(var r=0;r<t.length;r++)t[r]===n&&t.splice(r,1)}function v(e){return h[e]||[]}function g(e){return p[e]=p[e]||i(t)}function w(e,n){u(e,function(e,t){n=n||"feature",y[t]=n,n in s||(s[n]=[])})}var h={},y={},b={on:d,addEventListener:d,removeEventListener:m,emit:t,get:g,listeners:v,context:n,buffer:w,abort:a,aborted:!1};return b}function o(){return new r}function a(){(s.api||s.feature)&&(l.aborted=!0,s=l.backlog={})}var f="nr#context",c=e("gos"),u=e(4),s={},p={},l=n.exports=i();l.backlog=s},{}],gos:[function(e,n,t){function r(e,n,t){if(i.call(e,n))return e[n];var r=t();if(Object.defineProperty&&Object.keys)try{return Object.defineProperty(e,n,{value:r,writable:!0,enumerable:!1}),r}catch(o){}return e[n]=r,r}var i=Object.prototype.hasOwnProperty;n.exports=r},{}],handle:[function(e,n,t){function r(e,n,t,r){i.buffer([e],r),i.emit(e,n,t)}var i=e("ee").get("handle");n.exports=r,r.ee=i},{}],id:[function(e,n,t){function r(e){var n=typeof e;return!e||"object"!==n&&"function"!==n?-1:e===window?0:a(e,o,function(){return i++})}var i=1,o="nr#id",a=e("gos");n.exports=r},{}],loader:[function(e,n,t){function r(){if(!x++){var e=E.info=NREUM.info,n=d.getElementsByTagName("script")[0];if(setTimeout(s.abort,3e4),!(e&&e.licenseKey&&e.applicationID&&n))return s.abort();u(y,function(n,t){e[n]||(e[n]=t)}),c("mark",["onload",a()+E.offset],null,"api");var t=d.createElement("script");t.src="https://"+e.agent,n.parentNode.insertBefore(t,n)}}function i(){"complete"===d.readyState&&o()}function o(){c("mark",["domContent",a()+E.offset],null,"api")}function a(){return O.exists&&performance.now?Math.round(performance.now()):(f=Math.max((new Date).getTime(),f))-E.offset}var f=(new Date).getTime(),c=e("handle"),u=e(4),s=e("ee"),p=e(3),l=window,d=l.document,m="addEventListener",v="attachEvent",g=l.XMLHttpRequest,w=g&&g.prototype;NREUM.o={ST:setTimeout,SI:l.setImmediate,CT:clearTimeout,XHR:g,REQ:l.Request,EV:l.Event,PR:l.Promise,MO:l.MutationObserver};var h=""+location,y={beacon:"bam.nr-data.net",errorBeacon:"bam.nr-data.net",agent:"js-agent.newrelic.com/nr-1167.min.js"},b=g&&w&&w[m]&&!/CriOS/.test(navigator.userAgent),E=n.exports={offset:f,now:a,origin:h,features:{},xhrWrappable:b,userAgent:p};e(1),e(2),d[m]?(d[m]("DOMContentLoaded",o,!1),l[m]("load",r,!1)):(d[v]("onreadystatechange",i),l[v]("onload",r)),c("mark",["firstbyte",f],null,"api");var x=0,O=e(6)},{}],"wrap-function":[function(e,n,t){function r(e){return!(e&&e instanceof Function&&e.apply&&!e[a])}var i=e("ee"),o=e(5),a="nr#original",f=Object.prototype.hasOwnProperty,c=!1;n.exports=function(e,n){function t(e,n,t,i){function nrWrapper(){var r,a,f,c;try{a=this,r=o(arguments),f="function"==typeof t?t(r,a):t||{}}catch(u){l([u,"",[r,a,i],f])}s(n+"start",[r,a,i],f);try{return c=e.apply(a,r)}catch(p){throw s(n+"err",[r,a,p],f),p}finally{s(n+"end",[r,a,c],f)}}return r(e)?e:(n||(n=""),nrWrapper[a]=e,p(e,nrWrapper),nrWrapper)}function u(e,n,i,o){i||(i="");var a,f,c,u="-"===i.charAt(0);for(c=0;c<n.length;c++)f=n[c],a=e[f],r(a)||(e[f]=t(a,u?f+i:i,o,f))}function s(t,r,i){if(!c||n){var o=c;c=!0;try{e.emit(t,r,i,n)}catch(a){l([a,t,r,i])}c=o}}function p(e,n){if(Object.defineProperty&&Object.keys)try{var t=Object.keys(e);return t.forEach(function(t){Object.defineProperty(n,t,{get:function(){return e[t]},set:function(n){return e[t]=n,n}})}),n}catch(r){l([r])}for(var i in e)f.call(e,i)&&(n[i]=e[i]);return n}function l(n){try{e.emit("internal-error",n)}catch(t){}}return e||(e=i),t.inPlace=u,t.flag=a,t}},{}]},{},["loader"]);</script> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Adapter</title> <!-- DEPENDENCIES --> <link rel="shortcut icon" href="img/login_favicon.ico"> <link href="https://fonts.googleapis.com/css?family=Ubuntu:400,700,400italic" rel="stylesheet" type="text/css"> <link href="css/sportsbook.css" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Roboto:400,500,700"> <link href="css/demo.css" rel="stylesheet"> <link href="css/loginBetin.css" rel="stylesheet"> <link href="css/login.css" rel="stylesheet"> <link href="plugins/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet"> <script src="plugins/jquery-1.12.4/jquery.min.js"></script> <script src="plugins/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> <!-- Javascript client-side code --> <script type="text/javascript"> var lang = ""; function openSelection(mode, uri){ var url = "https://vsmobile.bet9ja.com" + uri + (uri.indexOf('?') ? "&mode=" : "?mode=") + mode + "&lang=" + lang; window.location.replace(url); } function backToMain(){ var url = "https://mobile.bet9ja.com/Mobile"; window.location.replace(url); } </script> <script type="text/javascript" src="js/grapi.js"></script> </head> <body> <div class="container" id="product" style="display: none"> </div> <div class="container" id="playarea" style=""> <script> var isLoaded = false; function onLoadIframe(iframe) { if (!isLoaded) { // iframe.src = '?game=league&OTP=98405c34-4f92-4db7-b993-7562953d2604&mode=premier&lang='; // './index-iframe-content.html' + window.location.search; if( iframe.src != "" ) { isLoaded = true; } } else { goBackUrl(); } } eventMethod = window.addEventListener ? "addEventListener" : "attachEvent"; eventer = window[eventMethod]; messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message"; eventer(messageEvent, function (e) { let data = e.data.split('$'); let command = data[0]; if (command == "goHome") { backToMain(); } }, false); </script> <div style="${bet9ja.iframe.style}"> <iframe id="playAreaFrame" onload="onLoadIframe(this)" style=" position:absolute;top:0;left:0;right:0;bottom:0;width:100%;height:100%;border:0; " src="https://vsmobile.bet9ja.com/mobile-1.94.35/themes/?sk=bet9ja&t=644ee448-8fb1-426c-9922-31688a0a85f6&pinHash=53a0d64f55b5986a27e81982ccd000de&pid=14001&v=0&text=Premier&homeUrl=https://mobile.bet9ja.com/Mobile&otp=98405c34-4f92-4db7-b993-7562953d2604&ss=&bl=&vu=0"> </iframe> </div> </div> <script type="text/javascript" charset="utf-8"> $(function() { var input = {"game":"league","OTP":"98405c34-4f92-4db7-b993-7562953d2604","mode":"premier","lang":""}; var u = "98405c34-4f92-4db7-b993-7562953d2604"; var home = ""; //"https://vsmobile.bet9ja.com/bet9ja-mobile/login/"; var params = "&pid=14001&v=0&text=Premier"; var game = "league_premier"; grapi.loggedUser(u,input,home,params,game,true ); }); </script> <script type="text/javascript">window.NREUM||(NREUM={});NREUM.info={"beacon":"bam.nr-data.net","licenseKey":"c95cd51526","applicationID":"214311961","transactionName":"ZlBXZxcAVkEHV0NbDV8aYEEMTlpXEg1dU09cWldaCQQXXglTXlxNWFtRVh1PSFoW","queueTime":0,"applicationTime":5,"atts":"ShdUEV8aRU8=","errorBeacon":"bam.nr-data.net","agent":""}</script> </body></html> I have tried to inspect the webpage using google chrome, and I have noticed that when I inspect the page the first time it shows (Please check the link for a screenshot): Screenshot of the code. The arrow points to the place where the code I need will be and when I inspect it for the second time I get the code I need. I have really invested a lot of time searching for any solutions, but I got nothing. I will be so happy to find a solution here. Thanks a lot
Thanks a lot #Sureshmani and #Anees Ijaz for your comments. So after you suggestions, the solution waas to switch to the iframe, so that's what solved my problem: iframe = driver.find_element_by_id('playAreaFrame') driver.switch_to.frame(iframe) print(driver.page_source) driver.switch_to.default_content() #To switch back to the original content Thanks a lot guys
Edit html div that has been copied into html file with jquery load
So I have a website with a Header.html. In the header are three buttons. I've copied the Header.html into all of my other pages with jquery's load. Now what I would like to do is change the colour of one of the buttons depending on the page it's on. But when I use document.GetElementById in javascript it can't find the div of the button I've copied from the Header.html Here's the Header.html <div id="Header_Wrapper"> <div id="Header_PageLinksWrapper"> <div class="Header_PageLink"> <a class="Header_PageLinkText" id="PageLink_Games" href="..\Pages\Games.html">Games</a> </div> <div class="Header_PageLink"> <a class="Header_PageLinkText" id="PageLink_AboutMe" href="..\Pages\AboutMe.html">About Me</a> </div> <div class="Header_PageLink"> <a class="Header_PageLinkText" id="PageLink_CV" href="..\Pages\CV.html">CV</a> </div> </div> </div> The javascript file: $(document).ready( function () { $("#Header").load("..\\Templates\\Header.html"); var filePath = window.location.pathname; SetPageLinkColours(filePath); } ); function SetPageLinkColours(aPath) { var firstIndex = aPath.lastIndexOf("/"); var lastIndex = aPath.indexOf(".html"); var id = "PageLink_" + aPath.slice(firstIndex + 1, lastIndex); var divElement = document.getElementById(id); if (divElement == null) { console.log("Could not find element " + id); } divElement.style.color = 0xffffff; } One of the pages (eg. Games.html) <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Adabelle Combrink - Games</title> <link rel="stylesheet" type="text/css" href="..\Templates\Header.css"/> <link rel="stylesheet" type="text/css" href="..\Templates\Page.css"/> <link rel="stylesheet" type="text/css" href="..\Pages\Games.css"/> <script type="text/javascript" src="..\Scripts\jQuery.js"></script> <script type="text/javascript" src="..\Scripts\Defaults.js"></script> </head> <body> <header> <div id="Header"></div> </header> </body> </html> What this gives me in the console is Could not find element PageLink_Games. I don't get that error if I use something that is in Games.html like Header. Is there any other way of doing the same thing. I know you can include files into eachother with php but I haven't gotten that right and don't seem to be able to run .php files in Visual Studio.
jQuery.load has a success callback. Use it to assure your code is only executed after the loading is complete. $(document).ready( function () { $("#Header").load("..\\Templates\\Header.html", null, function() { var filePath = window.location.pathname; SetPageLinkColours(filePath); }); } ); Also your SetPageLinkColours function can be improved with jQuery: function SetPageLinkColours(aPath) { var firstIndex = aPath.lastIndexOf("/"); var lastIndex = aPath.indexOf(".html"); var id = "PageLink_" + aPath.slice(firstIndex + 1, lastIndex); var divElement = $("#"+id); if (!divElement.length) { console.log("Could not find element " + id); } else { divElement.css('color','white'); } }
load function makes async request , so your code tries to find element before it rely appears. U need to use load function callback http://api.jquery.com/load/ $(document).ready( function () { $("#Header").load("..\\Templates\\Header.html", function () { var filePath = window.location.pathname; SetPageLinkColours(filePath); }); } );