Getting Wix HTML element into iFrame variable - javascript

I have a wix webpage with an HTML element on the page. I need to get the text of that element into my iFrame that contains javascript. I'd like to store that text of the html element as a variable in my iFrame javascript.
When I try the code below, my iFrame variable prints as 'undefined' in the web console.
<script>
var myElement = document.getElementById("#text15").text;
console.log(myElement);
</script>

The JavaScript function getElementById() receives as parameter the string of the id value it should search in the DOM. So, you are searching for this:
<div id="#text15"></div>
To find this element in the DOM:
<div id="text15"></div>
You could either do:
var myElement = document.getElementById("text15").innerText;
Or if you like using the hash symbol when referencing elements from the DOM, you can also try:
var myElement = document.querySelector("#text15").innerText;
Both work the same way. And also, use innerText which references as the content inside the tag. The text property of the DOM element returned by JavaScript does not exist.
Note: You should not reference your DOM elements right in a <script> tag. Since most likely the elements won't be ready by the time you call them.
Try:
<script>
window.onload = function() {
var myElement = document.getElementById("#text15").innerText;
console.log(myElement);
}
</script>
Look at an example of both ways:
var text1=document.querySelector("#myElement").innerText;
console.log(text1);
var text2=document.getElementById("myElement").innerText;
console.log(text2);
<div id="myElement">Hello!</div>

using jquery
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#inPut').click(function() {
var myElement =
$('#text15').val();
console.log(myElement);
});
});
</script>
</head>
<body>
<br>
<input type='text' id='text15'>
<button id='inPut'>Write to console</button>
<br>
</div>
</body>
</html>

Related

jquery accessing element via .html() returns undefined

I am new to jquery, I tried to access the input element via id , I see it returns "undefined" I wrapped it inside document.ready; result is the same, here is the code snippet
let input;
function maintest() {
input = $("<input>").attr({"id":"test"});
input.append("#mainDiv");
$(document).ready( function(){
alert($("#test").html());
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="maintest()">
<div id="mainDiv"></div>
</body>
I am surprised it shows "undefined" instead of showing the whole input element when I alert
You have several problems:
You never assigned anything to input before calling $(input). If you're trying to create an input element, you need to put a literal string <input> in the arguments.
You should use appendTo(), not append().
input elements aren't containers, they don't have any HTML in them, so .html() won't return anything (it's equivalent to .innerHTML, not .outerHTML). I changed the script to use $("#mainDiv").html(), then it show the <input> contained within it.
function maintest() {
let input = $("<input>").attr({
"id": "test"
});
input.appendTo("#mainDiv");
$(document).ready(function() {
alert($("#mainDiv").html());
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="maintest()">
<div id="mainDiv"></div>
</body>

How to get append value in jquery or other method?

How to get append value in jquery or other method?
I want to show the the value Hello Append!!! append value on <div id="get_append_value"></div> tag,
My Javascript code:
$(document).ready(function() {
$("#show_append_value").append("Hello Append!!!");
});
My Html code
<body>
<div id="show_append_value"></div>
<div id="show_hello_world">Hello World!!!</div>
<br>
<br>
<div id="get_append_value"></div <!--need to use jquery to show 'Hello Append!!! on it, but result is empty'-->
<div id="get_hello_world"></div>
</body>
<script>
var $show_value = $('#show_append_value').html();
$('#get_append_value').html($show_value);
var $show_value2 = $('#show_hello_world').html();
$('#get_hello_world').html($show_value2);
</script>
This result:
Hello Append!!!
Hello World!!!
Hello World!!!
Although it can show the value on <div id="show_append_value"> and <div id="show_hello_world">, it doesn't give the appended value to show on <div id="get_append_value"></div> , it is empty
Can anyone teach me how to get the appended value in jquery or other method to show the value on other div tag?
Your code executes in the wrong order.
Any code that is put directly in a script tag, outside of any call-back, is executed before what you have inside the ready call back, so that means Hello Append!! is not yet in your document when you are fetching it.
To solve this, put all of your code in the ready event handler:
$(document).ready(function() {
$("#show_append_value").append("Hello Append!!!");
var $show_value = $('#show_append_value').html();
$('#get_append_value').html($show_value);
var $show_value2 = $('#show_hello_world').html();
$('#get_hello_world').html($show_value2);
});

Javascript - include another script by using the <script> tag?

So I have a function that writes a string into a div.
The string is declared as content, which consists of html code, like this:
<h2>This is a test result</h2>
<script type="text/javascript" src="example_content.js"></script>
<script type="text/javascript"> document.write(example_content); </script>
where example_content.js :
example_content = '<p>some text some text some text some text some text</p>'
+ '<p>some more text....</p>'
+ '<hr />'
+ '<p>End of text</p>';
Problem is, instead of getting this in the div:
<h2>This is a test result</h2>
<p>some text some text some text some text some text</p>
<p>some more text....</p>
<hr />
<p>End of Text</p>
I end up, literaly, with this:
<h2>This is a test result/h2>
<script type="text/javascript" src="example_content.js"></script>
<script type="text/javascript"> document.write(example_content); </script>
Is there a way to avoid writting the script tag as a string ? but as an actual script ?
Thanks for any help in advance :)
You can't do that. You can't add script tags and execute them by writing the HTML. If you must load scripts dynamically, you should add them to the DOM. You can try this to load an external script file and execute the method.
(function(document){
var s = document.createElement('script');
s.id = "external_content";
s.async = true;
s.src = "example_content.js";
document.getElementsByTagName('head')[0].appendChild(s);
s.onload = function() {
document.write(example_content);
}
}(document));
What it basically does is that it creates a new script element dynamically and adds it to the DOM. It also sets an onload event handler which would fire once the script is downloaded completely.
I'm not sure about this question due to the wording however you don't need two <script> tags. At the end of the example_content.js place the document.write(example_content); then remove the <script type="text/javascript"> document.write(example_content); </script> from the html file.
Also if this is what you want I would recommend you use object.innerHTML rather than document.write and place the script at the bottom of your page.
if this doesn't work or isn't what you want please put a comment and I'll remove and use JSLint for an example.
Here's some info: https://developer.mozilla.org/en-US/docs/DOM/element.innerHTML
Okay so basically you want to write HTML inside the contents of your div. Say you have a div with the following id: myContentDiv
/**
* NOTICE HOW IM USING \ before " TO ESCAPE THE CHARACTERS INSIDE THE HTML STRING
*/
var yourCustomHTMLString = "<h1>this is a tag</h1><div class=\"yourClass\">something</div>";
var contentDiv = document.getElementById('myContentDiv');
contentDiv.innerHTML = yourCustomHTMLString;
Also, in your mark-up you need to specify a trigger for your JS, for instance an onload trigger.
window.onload = function(){
document.write(example_content);
}
And now say you want a function that will load an HTML string into a div.
function loadContent(HTMLstring, targetDivID)
{
var myDiv = document.getElementById(targetDivID);
myDiv.innerHTML = HTMLstring;
}
If you are trying to include a JS script inside another JS script, you need Ajax. If you are using a JS library, all common ones have a script load method predefined.
Dynamically load a JavaScript file
If I understand you correctly, you insert your content as innerHTML into a <div> , and the scripts don't execute.
As far as I know, this is the expected behavior, as there is no onLoad, document.ready etc. event when you alter the innerHTML of an element.
You could parse the inserted string for <script> nodes. Warning, this is a very "hacky" thing to do, usually there are better ways, for example using the success callback of the ajax functions of the various script libraries.
Nevertheless, here is what we used once. This needs to be executed after you inserted your content string. Please don't judge me, I was young and the time was short...
var div = document.getElementById("yourParentDiv");
if(div != null){
var x = div.getElementsByTagName("script");
for(var i=0;i<x.length;i++) {
eval(x[i].text);
}
}

Javascript Question regarding appendChild

Im just learning javascript and I'm just wondering why this doesn't work. I've created a button and when it is clicked I assigned a function which is supposed to append some text to all my paragraphs. I don't know why it doesn't work:
<html>
<head>
<title>javascript test</title>
</head>
<body>
<script language="javascript" type="text/javascript">
function appendStuff(){
var node = document.getElementsByTagName("P");
node.appendChild.createTextNode('Here's some text');
return true;
}
</script>
<noscript>
Your browser doesn't support javascript.
</noscript>
<input type="submit" value="click me" onclick="appendStuff();" />
<p>
This is the first paragraph.
</p>
<p>
This is the second paragraph.
</p>
<p>
This is the third paragraph.
</p>
</body>
</html>
you should pass new node as argument to appendChild method, like here:
var nodes = document.getElementsByTagName("P");
for(var i=0; i<nodes.length; i++) {
nodes[i].appendChild(document.createTextNode("Here's some text"));
}
document.getElementsByTagName returns a list (array) of element instead of just one, you have to pick up the one you'd like to append (i.e. node[0])
Try this
<html>
<body>
<script language="JavaScript">
function function11() {
var myNode = document.createTextNode("New Text Node");
document.body.appendChild(myNode);
}
</script>
<button onclick="function11();">Create text node</button>
</body>
</html>
function appendStuff(){
var node = document.getElementsByTagName("P");
var txt = 'Here is some text';
var newT = document.createTextNode(txt);
node.appendChild(newT);
return true;
}
Try the above method!!!!
> <script language="javascript"
> type="text/javascript">
The language attribute has been deprecated for over a decade, it should not be used.
> function appendStuff(){ var node = document.getElementsByTagName("P");
> node.appendChild.createTextNode('Here's some text');
> return true;
> }
As others have pointed out, getElemetsByTagName returns a live NodeList, which has a length property and whose members can be accessed by index. Note that while it is array-like, it is not an array.
A text element can be appended to the first node in the NodeList using:
node[0].appendChild(document.createTextNode("Here's some text"));
However it is much safer to first see if node[0] exists before attempting to call one of its methods.
> <noscript> Your browser doesn't
> support javascript. </noscript>
The fact that a browser displays a noscript element doesn't necessarily mean that the browser doesn't support javascript. The description of a noscript element includes:
The NOSCRIPT element allows authors to provide
alternate content when a script is not executed.
W3C, HTML4.01, ยง18.3.1
> <input type="submit" value="click me"
> onclick="appendStuff();" />
An input with a type of submit is intended to be in a form and be used to submit the form. A more appropriate value for the type attribute here is "button". And the XML-style closing tag is unnecessary.
document.getElementsByTagName return 'array' of fetched doms rather than one dom. so you need to specify single dom with for loop of this array or sth likely.

Can a JavaScript variable be used in plain HTML?

What I mean is, can a variable/array declared and initialized be used in HTML, outside the <script>-tags? Fx.
<script type="text/javascript">
var foo = array('placeholder1', 'placeholder2');
</script>
<body>
<p><!--access the variable here-->foo[0]</p>
</body>
How do you access the variable/array in this case? like this:
<p><script type="text/javascript">document.print(foo[0])</script></p>
??
Two ways to do this. This is the better one:
<script type="text/javascript">
// make sure to do this onLoad, for example jQuery's $()
var foo = array('placeholder1', 'placeholder2');
document.getElementById("fooHolder").innerHTML = foo.toString();
</script>
...
<p id="fooHolder"></p>
Or you could do it this way (which, as Marcel points out, doesn't work in XHTML and really shouldn't be used anyway):
<p><script type="text/javascript">document.write(foo)</script></p>
You can do something like this:
<script>
var str = 'hello there';
document.getElementById('para').innerHTML = str;
</script>
where an element has the specified id:
<p id="para"></p>
you simply cannot access javascript variable outside of the script tag, it is because,
Html does not recognise any variable it just renders the supported HTML elements
variables are used to store the temporary variables, that is for dynamic data, if you want something more dynamic then you can use PHP for that.
Unnecessarily verbose, but using standard DOM methods.
<script>
window.onload = function(){
// you do not need to initialize like this, but I like to
var bar1 = new String('placeholder1');
var bar2 = new String('placeholder2');
var foo = new Array();
// populate the Array with our Strings
foo.push(bar1);
foo.push(bar2);
// create an array containing all the p tags on the page
// (which is this case is only one, would be better to assign an id)
pArray = document.getElementsByTagName('p');
// create a text node in the document, this is the proper DOM method
bar1TextNode = document.createTextNode(foo[0].toString());
// append our new text node to the element in question
pArray[0].appendChild(bar1TextNode);
};
</script>
<body>
<p></p>
</body>
That's the only direct way you'll access it elsewhere in your page. By opening another script tag and printing it.
You can also use methods such as innerHTML to put the value somewhere.
I don't think you can access the javascript from html but you can set the innerhtml of a dom object through javascript so you may want to go the other way around. First google search I found so I cant promise its good but it has a quick sample.
http://www.tizag.com/javascriptT/javascript-innerHTML.php
You can even you AngularJS expression.
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.framework= "AngularJS";
});
</script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>I want to use variables directly in HTML using: {{ framework }}</p>
</div>
</body>
</html>
The above code will print out "I want to use variables directly in HTML using: AngularJS".You can use braces to write AngularJS expression. For example: {{ expression }}.

Categories

Resources