Search code examples
javascriptcss-selectorsselectors-api

JS querySelector: How to take HTML Tag data and hard code it into javascript without the need for HTML tags


I am trying to figure out what all its trying to get from the code below:

var svg   = document.querySelector('svg'),
path  = document.querySelector('path');
var code = document.querySelector('#code');

And the code that its referencing above is:

<textarea id="code">var curve = new CurveAnimator(
 [206,47], [182,280],
 [90,234], [273,101]
);

var o = document.getElementById('img');
o.style.position = 'absolute';

curve.animate(2, function(point,angle){
  o.style.left = point.x+"px";
  o.style.top  = point.y+"px";
  o.style.transform =
    o.style.webkitTransform =
    o.style.MozTransform =
    "rotate("+angle+"deg)";
});
</textarea>

<section>
<svg viewBox="0 0 450 370" width="400px" height="370px" xmlns="http://www.w3.org/2000/svg" class="content">
    <path d="M50,300 C50,100 350,100 350,300 " />
</svg>
</section>

The goal is to take those HTML code and place it within the javascript itself so its not looking for it in the tags in the HTML code. However, i am unable to find out what its getting from those querySelector in order to do that myself.

Any help would be great!

When i do alert(document.getElementById('code')); i get this:

enter image description here

Code string:

var code = "var curve = new CurveAnimator([206,47], [182,280],[90,234], [273,101]);var o = document.getElementById('img');
o.style.position = 'absolute';curve.animate(2, function(point,angle){o.style.left = point.x+""px"";o.style.top  = point.y+""px"";o.style.transform = o.style.webkitTransform =o.style.MozTransform =""rotate("" + angle + ""deg)"";});"

Solution

  • You're getting the right thing, if you want the content of #code, then you need to do

    alert(document.getElementById('code').innerHTML)
    

    all you're doing at the moment is finding the node called code

    to get that code onto the page you need to do this,

    var node = document.createElement("script");
    node.innerHTML = document.getElementById('code').innerHTML;
    document.getElementsByTagName("head").appendChild(node);
    

    this will extract the code from your textarea, create a script tag in the header, and add the content from your div..then the page will the code ready to use, and all you will have to do is invoke it.

    alternatively, you could have this content in a external js file and on document load add it to the page in a similar way...

    var node = document.createElement("script");
    node.setAttribute("href","js/curveanimate.js") 
    document.getElementsByTagName("head").appendChild(node)