简体   繁体   中英

Getting Wix HTML element into iFrame variable

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM