I have created a function that generates a number. I want to put the number into a span element. However, this will not work. The function works and if I put the number into a value box it works. These are the two parts of code pertaining to the question.
Code:
document.getElementById('average').innerhtml= averagescore
Average Score:<span id='average'> 0 </span>
The error might be with .innerhtml. You should write .innerHTML instead.
Note the 'HTML' is all caps.
Try this
document.getElementById('average').innerHTML = "your value"
Keep in mind the case-sensitivity of any programming language. JavaScript and jQuery are Case Sensitive Languages.
Two Variables like
var abc;
var ABC;
both are different. So same happens in your case innerHTML vs innerhtml, which are totally different.
Related
I have these two variables that I am trying to compare. They both have the same value, however, one is a href variable - meaning, it's being read from a file like this
<a href=http://google.com>Variable</a>
It's read like this, but displayed as an anchor tag in the browser, so when I go to compare a value using print "$collect_zids{$key} --> $temp";I see in the browser as
Variable --> Variable
How it appears in the browser. One text another link.
I'm assuming these two values are different hence why this code does not run
if($collect_zids{$key} eq $from_picture){
print "<h1>Hello</h1>";
}
Is there a way I can convert the href variable into a normal scalar variable so that I can compare them?
Thanks!
P.S. I think Javascript might be the only way, however, I don't have any experience with it.
There is no such thing as an "href variable". You have two scalar variables. One contains plain text and the other contains HTML. Your task is to extract the text inside the HTML <a> tag from the HTML variable and to compare that text with the text from the plain text variable.
One way to do that would be to remove the HTML from the HTML variable.
my $html = '<a href=http://google.com>Variable</a>';
my $text = 'Variable';
$html =~ s/<.+?>//g;
if ($html eq $text) {
say "Equal";
} else {
say "Not Equal [$html/$text]";
}
But it cannot be emphasised enough that parsing HTML using a regular expression is very fragile and is guaranteed not to work in many cases. Far better to use a real HTML parser. HTML::Strip is made for this very purpose.
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use HTML::Strip;
my $html = '<a href=http://google.com>Variable</a>';
my $text = 'Variable';
my $parser = HTML::Strip->new;
$html = $parser->parse($html);
if ($html eq $text) {
say "Equal";
} else {
say "Not Equal [$html/$text]";
}
It's also worth pointing out that this is answered in the Perl FAQ
How do I remove HTML from a string?
Use HTML::Strip, or HTML::FormatText which not only removes HTML but
also attempts to do a little simple formatting of the resulting plain
text.
Update: In a comment, you say
I have no way of using these methods since I am not explicitly defining the variable.
Which is clearly not true. How a variable is initialised has no bearing whatsoever on how you can use it.
I assume your HTML text is in the variable $from_picture, so you would strip the HTML with code like this:
my $parser = HTML::Strip->new;
my $stripped = $parser->parse($from_picture);
if($collect_zids{$key} eq $stripped){
print "<h1>Hello</h1>";
}
I have no idea where you got the idea that you couldn't use my solution because I was directly initialising the variables, where you were reading the data from a file. An important skill in programming is the ability to see through complex situations and extract the relevant details. It appears you need to do some more work in this area :-)
I found the answer using the Perl module HTML::FormatText;
use HTML::FormatText;
my $formatter = HTML::FormatText->new();
my $string = HTML::FormatText->format_file("path_to_the_file"); #$string variable to hold the result and the path must be for a file.
After using the HTML::FormatText module, I was able to get the raw string that was being read, instead of it being interpreted as HTML. So, I was getting <a href=http://google.com>Variable</a> returned, instead of just Variable. After getting the raw string, I could use regex to extract the parts that I needed.
Credit to - https://metacpan.org/pod/HTML::FormatText
I got a variable Javascrpit which has a number as a string in this case 0.84. I'm trying to convert it into a float but when I try to it appears a 0 as float instead the 0.84.
I'm using this:
var pot="0.84";
var asd = parseFloat(pot);
console.log(asd);
EDIT:
This is not exactly the example. I recover data from the HTML and it works for other numbers but not for this. It is difficult to explain my problem exactly. It is a lot of code and works for other numbers so don't know exactly.
Your input is not "0.84". If you test with that, you will get the correct answer. Your input has something else inside, like spaces, for example:
"0 .84"
This should be the solution:
parseFloat(pod.replace(/ /g, ""))
I have tried this example on my end and it completely worked. However, you can try to instead input the string value directly into the parse float() function and it should print our your expected value. If you still want to assign the parsefloat() to a variable, then try to either rewrite the code or re-open your IDE because the code should work.
var pot = "0.84"
console.log(parseFloat(pot))
or you can just write it in one line
console.log(parseFloat("0.84"))
Pretty simple question that I couldn't find an answer to, maybe because it's a non-issue, but I'm wondering if there is a difference between creating an HTML object using Javascript or using a string to build an element. Like, is it a better practice to declare any HTML elements in JS as JS objects or as strings and let the browser/library/etc parse them? For example:
jQuery('<div />', {'class': 'example'});
vs
jQuery('<div class="example></div>');
(Just using jQuery as an example, but same question applies for vanilla JS as well.)
It seems like a non-issue to me but I'm no JS expert, and I want to make sure I'm doing it right. Thanks in advance!
They're both "correct". And both are useful at different times for different purposes.
For instance, in terms of page-speed, these days it's faster to just do something like:
document.body.innerHTML = "<header>....big string o' html text</footer>";
The browser will spit it out in an instant.
As a matter of safety, when dealing with user-input, it's safer to build elements, attach them to a documentFragment and then append them to the DOM (or replace a DOM node with your new version, or whatever).
Consider:
var userPost = "My name is Bob.<script src=\"//bad-place.com/awful-things.js\"></script>",
paragraph = "<p>" + userPost + "</p>";
commentList.innerHTML += paragraph;
Versus:
var userPost = "My name is Bob.<script src=\"//bad-place.com/awful-things.js\"></script>",
paragraph = document.createElement("p");
paragraph.appendChild( document.createTextNode(userPost) );
commentList.appendChild(paragraph);
One does bad things and one doesn't.
Of course, you don't have to create textNodes, you could use innerText or textContent or whatever (the browser will create the text node on its own).
But it's always important to consider what you're sharing and how.
If it's coming from anywhere other than a place you trust (which should be approximately nowhere, unless you're serving static pages, in which case, why are you building html?), then you should keep injection in mind -- only the things you WANT to be injected should be.
Either can be preferable depending on your particular scenario—ie, if everything is hard-coded, option 2 is probably better, as #camus said.
One limitation with the first option though, is that this
$("<div data-foo='X' />", { 'class': 'example' });
will not work. That overload expects a naked tag as the first parameter with no attributes at all.
This was reported here
1/ is better if your attribubes depends on variables set before calling the $ function , dont have to concatenate strings and variables. Aside from that fact ,since you can do both , and it's just some js code somebody else wrote , not a C++ DOM API hardcoded in the browser...
What I'm attempting to do can be accomplished by the following...
elementContent = document.getElementById('docElement').innerHTML;
elementContent = parseFloat(elementContent);
or even by...
elementContent = parseFloat( document.getElementById('docElement').innerHTML );
but I can't help to wonder if there's a more elegant way to retrieve and assign DOM content as a float that I may be unaware of. Any insight?
There is the unary plus operator which tries to convert a string (or another type's toString()) to a number. It would be used like:
elementContent = +document.getElementById('docElement').innerHTML;
As others have mentioned you can use jQuery as essentially syntactic sugar for .innerHTML here, also.
That's a fine way to go about doing things. The only thing I could suggest would be that if you can avoid working with the HTML markup entirely, by storing the "clean" number as an attribute of the element, that would be preferable, as it would get around problems that might be introduced if the HTML gets fancier than you expect it to be. (For example, sometimes designers want negative numbers formatted with the Unicode "minus" glyph instead of the plain hyphen, because it looks better.)
Thus if you could generate your elements like this:
<span id='docElement' data-value='29.20221'>29.20221</span>
then instead of accessing the value as ".innerHTML" you'd use ".getAttribute()":
var value = document.getElementById('docElement').getAttribute('data-value');
value = parseFloat(value);
Use JQuery:
var html = parseFloat($('#docElement').html());
$('#docElement').html(html);
If you use a library such as jQuery the code for this would be more elegant, like so:
var el = parseFloat( $('#docElement').text() );
Don't forget you might run into an issue where you need to trim() the string as well.
I have the following
var id='123';
newDiv.innerHTML = "";
Which renders in my HTML.
The problem I have is that I wish to take the call to the method TestFunction, and use as a string parameter in my function StepTwo(string, boolean), which would ideally end up in live HTML as shown...
notice how the TestFunction is a string here (it is executed within StepTwo using eval).
I have tried to format my JS as by :
newDiv.innerHTML = "";
but while this appears to me correct in my IDE, in the rendered HTML, it as garbelled beyond belief.
Would appreciate if anyone could point me in the right direction. Thanks!
One of the biggest capital failures on the internet is creating html in javascript by gluing strings together.
var mya = document.createElement("a");
mya.href="#";
mya.onclick = function(){
StepTwo(function(){
TestFunction('123', false );
}, true );
};
newDiv.innerHTML = "";
newDiv.appendChild(mya);
This Eliminates the need for any fancy escaping stuff.
( I probably should do 'onclick' differently, but this should work, I'm trying hard not to just use jQuery code to do everything )
Heres how I would do it in jQuery:
jQuery(function($){
var container = $("#container");
var link = document.createElement("a"); /* faster than $("<a></a>"); */
$(link).attr("href", "Something ( or # )" );
$(link).click( function(){
var doStepTwo = function()
{
TestFunction('123', true );
};
StepTwo( doStepTwo, false ); /* StepTwo -> doStepTwo -> TestFunction() */
});
container.append(link);
});
There is no good excuse for gluing strings together in Javascript
All it does is ADD overhead of html parsing back into dom structures, and ADD potential for XSS based broken HTML. Even beloved google get this wrong in some of their advertising scripts and have caused epic failures in many cases I have seen ( and they don't want to know about it )
I don't understand Javascript is the only excuse, and it's NOT a good one.
Try using " instead of \"
newDiv.innerHTML = "<a href="#"...
You should be using " not " or \" inside an HTML string quoted with double-quotes.
NewDiv.innerHTML = "";
There's probably a better way to do this - any time you find yourself using eval() you should stand back and look for a different solution.
You claim that eval is the right thing to do here. I'm not so sure.
Have you considered this approach:
and in your StepTwo function
function StepTwo(func,args,flag){
//do what ever you do with the flag
//instead of eval use the function.apply to call the function.
func.apply(args);
}
You could create the a element and attach to the click event using DOM Methods.
A Javascript Framework (like the ubiquitous jQuery) would make this a lot easier.
Your biggest problem is using eval, it leads to so many potential problems that it's nearly always better to find an alternative solution.
Your immediate problem is that what you really have is
as the next " after the start of the onclick attribute, closes it. Use " as others have suggested. And don't use eval.
You need to alternate your " and '.
Maybe you don't need quotes around the 123, because of Javascripts flexible typing. Pass it without quotes but treat it as a string within TestFunction.
Hey guys, thanks for all the answers. I find that the quot; seems to work best.
I'll give you guys some votes up once I get more reputation!
In regards to eval(), what you see in the question is a very small snapshot of the application being developed. I understand the woes of eval, however, this is one of those one in a million situations where it's the correct choice for the situation at hand.
It would be understood better if you could see what these functions do (have given them very generic names for stackoverflow).
Thanks again!
The best way is to create the element with document.createElement, but if you're not willing to, I guess you could do or use ".
In your code:
newDiv.innerHTML = "";
If it doesn't work, try changing "\'" to "\\'".
Remember that the " character is used to open and close the attribute on HTML tags. If you use it in the attribute's value, the browser will understand it as the close char.
Example:
<input type="text" value="foo"bar"> will end up being <input type="text" value="foo">.
...
I know this is hella' old now, but if anyone has issues with escaped strings when using eval (and you absolutely have to use eval), I've got a way to avoid problems.
var html = '';
eval('(function(div, html){div.innerHTML = html;})')(newDiv, html);
So, what's going on here?
eval creates a function that contains two parameters, div and html and returns it.
The function is immediately run with the parameters to the right of the eval function. This is basically like an IIFE.
In this case
var myNewMethod = eval('(function(div, html){div.innerHTML = html;})');
is basically the same as:
var myNewMethod = function(div, html){div.innerHTML = html;}
and then we're just doing this:
myNewMethod(newDiv, html); //where html had the string containing markup
I would suggest not using eval. If it can't be avoided, or if you control all the inputs and there's no risk of injection then this will help in cases where string escapes are an issue.
I also tend to use Function, but it isn't any more secure.
Here's the snippet I use:
var feval = function(code) {
return (new Function(code))();
}