Browzer adds paragraph elements inside script - javascript

I am new to web developing, and I have met this problem. I write the following script:
<script>
function updateProductQuantity(num,index)
{
var inp = document.getElementById("input-"+index);
var tot = document.getElementById("total-"+index);
var n_quantity = inp.value;
if (!isNaN(n_quantity))
{
addArticle(num, null, {"quantity":"set_"+n_quantity});
inp.value = parseInt(inp.value);
}
else window.alert("Not a number: " + n_quantity);
}
</script>
In chorme, (also firefox) this appears like this:
<p> <script>
function updateProductQuantity(num,index)
{
var inp=document.getElementById("input-"+index);
var tot=document.getElementById("total-"+index);
var n_quantity=inp.value;</p>
<p> if (!isNaN(n_quantity))
{
addArticle(num,null, {"quantity":"set_"+n_quantity});
inp.value = parseInt(inp.value);
}
else window.alert("Not a number:" + n_quantity);
}
</script></p>
(both firefox and chrome insert these p tags)
In the browzer, the whole script appears to be inside a "p" element, which I do not write in the code.
Also, the empty lines of my code are converted into p tags.
Of course, the script is broken and I get this error:
Uncaught SyntaxError: Unexpected token <
A workaround is to remove all empty lines from the come. But I dont think this is a solution. Right?
Thanks in advance!

Without seeing all of your code my best guess would be that you've got something else going on like an unclosed tag that is confusing matters.
Try putting the contents of your file through W3C's validator https://validator.w3.org/#validate_by_input and fix any errors that it is showing you

Related

How to select/hide elements inside an object of type "text/html" using javascript [duplicate]

I'm using the object tag to load an html snippet within an html page.
My code looks something along these lines:
<html><object data="/html_template"></object></html>
As expected after the page is loaded some elements are added between the object tags.
I want to get those elements but I can't seem to access them.
I've tried the following
$("object").html() $("object").children() $("object")[0].innerHTML
None of these seem to work. Is there another way to get those elements?
EDIT:
A more detailed example:
consider this
<html><object data="http://www.YouTube.com/v/GGT8ZCTBoBA?fs=1&hl=en_US"></object></html>
If I try to get the html within the object I get an empty string.
http://jsfiddle.net/wwrbJ/1/
As long as you place it on the same domain you can do the following:
HTML
<html>
<object id="t" data="/html_template" type="text/html">
</object>
</html>
JavaScript
var t=document.querySelector("#t");
var htmlDocument= t.contentDocument;
Since the question is slightly unclear about whether it is also about elements, not just about the whole innerHTML: you can show element values that you know or guess with:
console.log(htmlDocument.data);
The innerHTML will provide access to the html which is in between the <object> and </object>. What is asked is how to get the html that was loaded by the object and inside the window/frame that it is producing (it has nothing to do with the code between the open and close tags).
I'm also looking for an answer to this and I'm afraid there is none. If I find one, I'll come back and post it here, but I'm looking (and not alone) for a lot of time now.
No , it's not possible to get access to a cross-origin frame !
Try this:
// wait until object loads
$('object').load(function() {
// find the element needed
page = $('object').contents().find('div');
// alert to check
alert(page.html());
});
I know this is an old question, but here goes ...
I used this on a personal website and eventually implemented it in some work projects, but this is how I hook into an svg's dom. Note that you need to run this after the object tag has loaded (so you can trigger it with an onload function). It may require adaptation for non-svg elements.
function hooksvg(elementID) { //Hook in the contentDocument of the svg so we can fire its internal scripts
var svgdoc, svgwin, returnvalue = false;
var object = (typeof elementID === 'string' ? document.getElementById(elementID) : elementID);
if (object && object.contentDocument) {
svgdoc = object.contentDocument;
}
else {
if (typeof object.getSVGDocument == _f) {
try {
svgdoc = object.getSVGDocument();
} catch (exception) {
//console.log('Neither the HTMLObjectElement nor the GetSVGDocument interface are implemented');
}
}
}
if (svgdoc && svgdoc.defaultView) {
svgwin = svgdoc.defaultView;
}
else if (object.window) {
svgwin = object.window;
}
else {
if (typeof object.getWindow == _f) {
try {
svgwin = object.getWindow();//TODO look at fixing this
}
catch (exception) {
// console.log('The DocumentView interface is not supported\r\n Non-W3C methods of obtaining "window" also failed');
}
}
}
//console.log('svgdoc is ' + svgdoc + ' and svgwin is ' + svgwin);
if (typeof svgwin === _u || typeof svgwin === null) {
returnvalue = null;
} else {
returnvalue = svgwin;
}
return returnvalue;
};
If you wanted to grab the symbol elements from the dom for the svg, your onload function could look like this:
function loadedsvg(){
var svg = hooksvg('mysvgid');
var symbols = svg.document.getElementsByTagName('symbol');
}
You could use the following code to read object data once its loaded completely and is of the same domain:
HTML-
<html>
<div class="main">
<object data="/html_template">
</object>
</div>
</html>
Jquery-
$('.main object').load(function() {
var obj = $('.main object')[0].contentDocument.children;
console.log(obj);
});
Hope this helps!
Here goes a sample piece of code which works. Not sure what the problem is with your code.
<html>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var k = $("object")[0].innerHTML;
alert(k);
$("object")[0].innerHTML = "testing";
});
</script>
<object data="/html_template">hi</object>
</html>
UPDATED
I used this line of Javascript to change the value of a input filed inside an iFrame, taken from How to pick element inside iframe using document.getElementById:
document.getElementById('iframeID').contentWindow.document.getElementById('inputID').value = 'Your Value';
In your case, since you do not have a frame, and since you want to get and not set the value, log it for example with:
console.log(document.getElementById('object').value);
And if you guess or choose an element:
console.log(document.getElementById('object').data);

getElementByID() function is returning null value [duplicate]

This question already has answers here:
Javascript can't find element by id? [duplicate]
(5 answers)
Closed 4 years ago.
The following line of code (in my Javascript file) :-
var header = document.getElementById("theheader");
is resulting in header having a "null" value. Here, "theheader" is the ID of a "h2" type header in my HTML file.
The desired output is:-
<h2 id="theheader" style="color: rgb(114, 58, 76);">
The script tag of the JS file is defined within the head element of the HTML file.
The same line of code would work perfectly in any browser console by giving the desired output i.e.
Even though this issue has been handled before, I could not find the answer as to why the same code above is working in the browser console and not working in IDE's like VSCode, Atom and others?
I would be thankful if anyone could provide me the answer for the above query, specially the one in bold font.
One possible reason could be that your code is running before the DOM is fully loaded. Wrap your code with DOMContentLoaded:
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
<script>
document.addEventListener("DOMContentLoaded", function(event) {
//Intro
alert("Hey! Welcome to my page!!");
var a = prompt("How are you today?");
alert("Happy to know that you are " + a);
var header = document.getElementById("theheader");
console.log("h2 is " + header);
header.style.color = "red";
function getRandomColor() {
var letters = "0123456789ABCDEF";
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeHeaderColor(){
colorInput = getRandomColor()
header.style.color = colorInput;
}
setInterval(changeHeaderColor,500);
});
</script>
<h2 id = "theheader"> Arnab Sinha </h2>

Changing image SRC using javascript - unknown error

I'm using javascript for the first time and am having difficulty getting certain features to work. Crucially I can't seem to get the following line of code to execute.
document.getElementByID("reportImage").src=filepath;
The full code is given below.
Notice that I've created a test function to try and narrow down the cause of the malfunction. The first two functions are there to demonstrate intent but are not currently being called by the .
The behavior of the test function suggests that the error is within this specific line. Notably the alert will fire if it is placed first in the function but will not trigger if placed second (suggesting that this specific line is problematic in some way).
It may be a simple syntax error but I've checked many times and can't see what it might be. Please help!
<!DOCTYPE html>
<html>
<script>
/* declare and set script variables */
var numberOfImages, imageArray, timing, containingFolder, i;
i = -1;
timing = 3;
containingFolder = "H:\\Images";
imageArray = [
"FoxKey.jpg",
"TeamKPI2.tif"
]; //imageArray should contain names of image files that sit within the specified folder
numberOfImages = imageArray.length;
function activateImageTimer() {
/* function iterates through selected images */
if (numberOfImages === timingArray.length) {
setInterval(nextImage(), timing*10);
}
else { alert("Please check contents of imageArray and timingArray. The
number of images should correspond to the number of timings."); }
}
function nextImage() {
i = (i+1) % numberOfImages; //use modulus function to loop through array
var filepath = containingFolder + "\\" + imageArray[i]; //build filepath
document.getElementByID("reportImage").src=filepath;
}
function testFunction() {
document.getElementByID("reportImage").src="H:\\Images\\FoxKey.jpg";
alert("Function is functioning");
}
</script>
<body onload="testFunction()">
<img id="reportImage" src="H:\Images\TeamKPI2.tif">
</body>
</html>
JavaScript is Case Sensitive.
Try with this:
Change: document.getElementByID to document.getElementById
And, <script></script> it has to be put inside the body or head, not of html.

Find specific div with RegEx and print content

I'm trying to pull some text from an external website using this script.
It works perfectly, but it gets the entire page. I want to take only the content inside a specific div with the class 'content'. The entire page is put inside the variable 'data', and then this function is created to strip some tags:
function filterData(data){
data = data.replace(/<?\/body[^>]*>/g,'');
data = data.replace(/[\r|\n]+/g,'');
data = data.replace(/<--[\S\s]*?-->/g,'');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
data = data.replace(/<script.*\/>/,'');
return data;
}
How would I go about finding the div with the class 'content' and only viewing the content inside that?
UPDATE: Sorry about using RegExes — can you help me to get the content without using RegEx? So, this is my HTML file:
erg
<div id="target" style="width:200px;height:500px;"></div>
<div id="code" style="width:200px;height:200px;"></div>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(document).ready(function(){
var container = $('#target');
$('.ajaxtrigger').click(function(){
doAjax($(this).attr('href'));
return false;
});
function doAjax(url){
if(url.match('^http')){
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=xml'&callback=?",
function(data){
if(data.results[0]){
var tree = string2dom(data.results[0]);
container.html($("div.content", tree.doc));tree.destroy();
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
}
);
} else {
$('#target').load(url);
}
}
function filterData(data){
return tree;
}
});
</script>
Try something like this:
var matches = data.match(/<div class="content">([^<]*)<\/div>/);
if (matches)
return matches[1]; // div content
try this:
<div\b[^>]*class="content"[^>]*>([\s\S]*?)<\/div>
Here try this :
<div[^>]*?class='content'[^>]*?>(.*?)</div>
Captured reference /1 will have your content. Although you shouldn't be doing this with regexes :)
this may help you:
var divtxt = match(/<div[^>]*class="content"[^>]>.*<\/div>/);
but it may stop at the wrong .
you should use jquery or prototype to make it a dom-object and use selectors to find the right div.
using jquery you would do something like:
var divtxt = $(data).find(".content").first().html();
remember to load the jquery library first.

Why the value inside the loop and using the [i] is undefined?

using Mozilla jetpack , when i do the following code .. i get that linking is undefined !!! why ? or how to fix it ?
var links = doc.querySelectorAll('#courses_menu > ul > li > a');
var linkz=links[1].href.split("?");
var i = 0;
for (i=0;i<=4;i++)
{
var linking= links[i];
}
jetpack.notifications.show(" "+ linking);
Because it goes out of scope when the loop ends.
So you should have
var linking;
for (i=0;i<=4;i++)
{
linking= links[i];
}
But furthermore, what are you trying to do here? You overwrite linking four times. Do you want to display all of the links? If so, you can concatenate them like:
var linking = "";
for (i=0;i<=4;i++)
{
linking = linking + links[i] + " ";
}
Edit: the commenters are right; I did forget that there is no block scoping in Javascript. Did this fix your code? I can't imagine that it did. The only other thing that I can think of is that links[4] is undefined, and then you would be assigning undefined to linking.
Anyway, I can't delete this because it's been accepted, but if anyone else comes up with a more useful answer, feel free to unaccept this one.

Categories