Properly declaring a variable - javascript

I don't know how to declare a variable here in javascript. I have an example situation that if the paragraph is equals to a, the alert will popup.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="sample">a</p>
</body>
</html>
<script type="text/javascript">
var sample = getElementById('sample');
if (sample == "a") {
alert("Correct")
};
</script>

You're declaring your variable just fine, however if you want the text within the element, you also need to use the innerHTML property. And when you use the getElementById method, you need to use it on the document object like document.getElementById:
var sample = document.getElementById('sample');
if (sample.innerHTML == "a") {
alert("Correct")
};
<p id="sample">a</p>

sample is a variable and you are correct but it is storing a reference to a DOM Element with id sample. To get the inner html of that you need
var sample = getElementById('sample').innerHTML;
Also, use === over == for no casting etc. Refer here
I will recommend you to have a quick look at JS from w3schools and then move to MDN. Nobody will report you here if you show your efforts, so relax :).

Your declaration is fine, but the assignment part is missing document as the object which has the .getElementById method. Then, once you have the reference to the element, you then need to access its content with .textContent (you can't compare the entire element to a value that the element might contain). As a side note on this, when the string you wish to set/get doesn't contain any HTML, you should use .textContent so that the browser doesn't parse the string for HTML unnecessarily. Often, people will suggest that the content of an element should be gotten/set using .innerHTML and, while that will work, it's wasteful if the string doesn't contain any HTML.
Also, the <script> must be located within the head or the body, not outside of them. I would suggest placing it just prior to the closing body tag so that by the time the processing reaches the script, all of the HTML elements have been parsed into memory and are available.
Lastly (and this is really just a side point), an HTML page also needs the title element to have something in it, otherwise it won't be valid. While browsers don't actually do HTML validation, it's important to strive for valid HTML so that you can be sure that your pages will work consistently across all devices. You can validate your HTML at: http://validator.w3.org.
<!DOCTYPE html>
<html>
<head>
<title>Something Here</title>
</head>
<body>
<p id="sample">a</p>
<script type="text/javascript">
var sample = document.getElementById('sample');
if (sample.textContent == "a") {
alert("Correct")
};
</script>
</body>
</html>

Related

Javascript display an html pge from a variable containing code

In my project i have a javascript file that contain a variable like this one:
var htmlcode = "<html><body><h1>My First Web Page</h1><p>My first paragraph.</p></body></html>"
i would to know if in javascript exist a command for render my htmlcode variable ina real html page, i think to use a button for open that page.
So many thanks in advance
Using jQuery, you can use $('html') to select the HTML tag, and change its content using $('html').html("some new content"):
$("#changeHTML").click(function() {
$('html').html("<body><div style='color:red;'>New sample text</div></body>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
Sample text
<button id="changeHTML">Click me</button>
</body>
</html>
Using plain Javascript, you can use document.documentElement to select the document's HTML tag (source), and changing this variable's innerHTML should do the trick.

How to parse HTML tags from JSON Object

I have a json object which has a value of html with styles. I tried including it in my html using jquery append.
the value is getting appending, but it is not converting into normal DOM, it is appending the whole thing as a string.
This is my JSON object value:
var obj = {
content : "<p><linkrel="stylesheet"type="text/css"href="http:<p><styletype="text/css"><br/>.wrap{<br/> background-color:#F6F6F6;<br/>}<br/></style></p><p><divclass="wrap"><br/> </div></p>"
}
This is what i tried:
HTML:
<div id='container'></div>
JS:
$('#container').append(obj.content);
Demo
Output should be a part of dom, instead it is printing the entire thing as a string.
Can you trying doing:
$('#container').append($(obj.content));
That should work. As you are just trying to append text and not DOM elements
Another change being the response JSON, as it has p tags and htmlescaped elements. So, you might have to change the response a bit too, For instance,
Changing the stylesheet link to a style tag, attached to the div.
send the response back as unescaped, which will help reduce the clutter.
Hope that helps!
You can do something like this ...
var obj = {
content : '<p><style>.wrap{color:red}</style><div class="wrap">aa</div></p>'
}
$('span').append($(document.createElement('div')).html(obj.content).text());
fiddler: https://jsfiddle.net/suscmguy/
Your obj.content seems to have invalid / incomplete encoding
Hope this helps...
Your string formatting is wrong because when i replaced your code with the following code it worked perfectly fine
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div id='tester'></div>
<script >
var obj = {
content : "<ul><li>coffee</li><li>tea</li></ul>'"
};
$('#tester').append(obj.content);
</script>
</body>
</html>
what i mean to say is you think you are adding a html code but because of your bad string formatting javascript thinks it is a simple string and that is why u see a string added.

Using getElementByID.innerHTML from within a switch statements case?

Alright so first off, total Newbie here, so my questions answer might be extreemley simple because i have missed some thing critical.
I am trying to have a switch statement, switch out the innerHTML of an h1 tag with an id="bbref". I set the userName Variable to "Lister" and created my switch statement to write a different line into the h1 tag base don what name was input for userName.
for some reason however my code is just not working... any thoughts.. or noticeable brain-farts on my end?
here is the code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Javascript Learning</title>
<script type="text/javascript">
var userName = "Lister";
switch (userName) {
case "Lister" :
document.write.getElementById("bbref").innerHTML = "Lister Is the Man!";
break;
case "Rimmer":
document.write.getElementById("bbref").innerHTML = "Rimmer is a Smeg head...";
break;
default :
doacument.write.getElementById("bbref").innerHTML = "It's all about \"The Cat\""
}
</script>
</head>
<body>
<header></header>
<section>
<article>
<h1 id="bbref">Test Title</h1>
</article>
</section>
<footer></footer>
</body>
</html>
You're messing up your functions a little there, change:
document.write.getElementById("bbref").innerHTML = "Lister Is the Man!";
to:
document.getElementById("bbref").innerHTML = "Lister Is the Man!";
And so on for the rest.
document.getElementById("bbref") will fetch the element and .innerHTML will be the HTML inside the element, changing it will directly change the visible HTML. So there's no need to write anything.
Fiddle:
http://jsfiddle.net/H4hzE/
window.onload/$(document).ready()
The other issue you would be having here is that your javascript code is executing before your HTML is rendering. Bind your code to window.onload or $(document).ready() (if using jQuery) to run the code after the page loads.
window.onload Examples:https://developer.mozilla.org/en-US/docs/DOM/window.onload
jQuery's $(document).ready():http://api.jquery.com/ready/
Fiddle (using window.onload):
http://jsfiddle.net/H4hzE/1/
Since you say you're new to JavaScript, it's probably worthwhile sharing some info regarding document.write() as I think you may have misunderstood it's functionality a little bit. :)
http://www.w3schools.com/jsref/met_doc_write.asp
http://javascript.info/tutorial/document-write
https://developer.mozilla.org/en-US/docs/DOM/document.write
document.write() and document.getElementById() are two different methods. In this case you just want to use getElementById, so omit the .write in all 3 cases, e.g.:
document.getElementById("bbref").innerHTML = "Lister Is the Man!";

how to get script inside content see example below

I want to get content of script tag example
now see above in src property load bolo7.com content i want to catch that contain
i have try so many method but it doesn't work
try 1 -> document.getElementById("data").innerHTML; //doesn't work
try2 -> document.getElementById("data").text; //doesn't work
if you are intelligent in javascript please give me answer that how to get content of script inside content
thanks in advance for your answer
my website is : http://www.bolo7.com/
The text property defined by the HTMLScriptElement interface is the text content of the script element. If the element uses a src attribute, it should not have any content so its text property will be an empty string.
In that case, you will need to access the src some other way, perhaps XMLHttpRequest will suit.
Note also that the id attribute for script elements is not valid for the DOCTYPE being used at the linked resource (and the document is invalid).
Something like this?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
//some data here
function add1(x) {
return 1 + x;
}
</script>
<script type="text/javascript">
alert(document.getElementsByTagName("script")[0].innerHTML);
</script>
</head>
<body>
</body>
</html>
but RobG is right, only works for inline javascript.

how does a function know where it is located in the DOM?

I'm trying to write a javascript function that adds some DOM nodes to the document in the place it was called, like this:
...
<div>
<script type="text/javascript">
pushStuffToDOMHere(args);
</script>
</div>
...
i try to do it 'cleanly', without using node id property of the div, or innerHTML string manipulation. for that I need to know where in the document the script tag is located.
is there a way to do it?
Talking about cleanly, I don't think your approach is particularly clean. It is a much better idea to give the div a unique id and execute your javascript when the DocumentReady-event fires.
Do you have an overriding reason for doing it this way? If not the suggestion to use a unique id makes the most sense. And you can always use a library like jQuery to make this even easier for yourself.
However, the following quick test shows that if you use document.write() in the function then it writes the value into the place where the function was called from.
<html>
<head>
<script type="text/javascript">
function dosomething(arg){
document.write(arg);
}
</script>
</head>
<body>
<div>The first Div</div>
<div>The
<script type="text/javascript">
dosomething("Second");
</script>
Div
</div>
<div>The
<script type="text/javascript">
dosomething("Third");
</script>
Div
</div>
</body>
</html>
But, again the question, are you sure this is what you want to do?
Although I agree with n3rd and voted him up, I understand what you are saying that you have a specific challenge where you cannot add an id to the html divisions, unless by script.
So this would be my suggestion for inlining a script aware of its place in the DOM hierarchy, in that case:
Add an id to your script tag. (Yes, script tags can have ids, too.)
ex. <script id="specialagent" type="text/javascript">
Add one line to your inline script function that gets the script element by id.
ex. this.script = document.getElementById('specialagent');
...And another that gets the script element's parentNode.
ex. var targetEl = this.script.parentNode;
Consider restructuring your function to a self-executioning function, if you can.
Ideally it executes immediately, without the necessity for an 'onload' call.
see summary example, next.
SUMMARY EXAMPLE:
<script id="specialagent" type="text/javascript">
var callMe = function(arg1,arg2,arg3) {
this.script = document.getElementById('specialagent');
var targetEl = this.script.parentNode.nodeName=="DIV" && this.script.parentNode;
//...your node manipulation here...
}('arg1','arg2','arg3');
</script>
The following TEST code, when run, proves that the function has identified its place in the DOM, and, importantly, its parentNode. The test has division nodes with an id, only for the purpose of the test. They are not necessary for the function to identify them, other than for testing.
TEST CODE:
<html>
<head>
<title>Test In place node creation with JS</title>
</head>
<body>
<div id="one">
<h2>Child of one</h2>
<div id="two">
<h2>Child of two</h2>
<script id="specialagent" type="text/javascript">
var callMe = function(arg1,arg2,arg3) {
this.script = document.getElementById('specialagent');
var targetEl = this.script.parentNode;
/*BEGIN TEST*/
alert('this.script.id: ' + this.script.id);
alert('targetEl.nodeName: ' + targetEl.nodeName + '\ntargetEl.id: '+targetEl.id);
alert('targetEl.childNodes.length: ' + targetEl.childNodes.length);
var i = 0;
while (i < targetEl.childNodes.length) {
alert('targetEl.childNodes.'+i+'.nodeName = ' + targetEl.childNodes[i].nodeName);
++i;
}
/*END TEST - delete when done*/
//...rest of your code here...to manipulate nodes
}('arg1','arg2','etc');
</script>
</div>
</div>
</body>
</html>
Not really sure what your trying to achieve but this would pass the dom element to the function when clicked. You could then use jquery in the function to do what you wanted like so
...
<script type="text/javascript">
function pushStuffToDOMHere(element)
{
$(element).append("<p>Hello</p>"); // or whatever
}
</script>
<div onclick="pushStuffToDOMHere(this);">
</div>
...
my solution is a compbination of the (good) answers posted here:
as the function is called, it will document.write a div with a unique id.
then on document.onload that div's parent node can be easily located and appended new children.
I chose this approach because some unique restrictions: I'm not allowed to touch the HTML code other than adding script elements. really, ask my boss...
another approach that later came to mind:
function whereMI(node){
return (node.nodeName=='SCRIPT')? node : whereMI(node.lastChild);
}
var scriptNode = whereMI(document);
although, this should fail when things like fireBug append themselves as the last element in the HTML node before document is done loading.

Categories

Resources