px06 px06 - 3 months ago 32
Javascript Question

Is it possible to output something not in an element in Javascript?

I'm not sure if this is a stupid question (I sense downvotes) but I searched online and haven't been able to find any useful information.

If I want display something on the page I can use:

document.getElementById("id").value="whatever";


Is it possible to get rid of the notion of having elements here so that I can do something like:

<html>
<body>
<script>write something here with javascript, no need for element?</script>
</body>
</html>


I know this can be achieved by using something like:

function e(){
return "whatever";
}


But I'm trying to use this QRCode generator which requires an ID. However I'm dynamically generating a few rows of QR codes in a
c:forEach
loop with
JSP
and I can't figure out how to display a QR code for each iteration of the loop.

JSP context:

<c:forEach items="item" var="${items">

<!-- display QR code here with value from ${item.qr} -->

</c:forEach>


This is what happens when I use something like:

<c:forEach items="item" var="${items}">

<script>
new QRCode(document.getElementById("qrcode"), "${item.qr}");
</script>

<div id="qrcode"></div>

</c:forEach>


Result:

enter image description here

Fixed by doing:

<c:forEach items="item" var="${items">

<script>
var div = document.createElement("div");
div.id = "${item.id}";
new QRCode(document.getElementById("${item.id}"), "${item.qr}");
</script>

</c:forEach>

mmm mmm
Answer

You can create an element and it's text like this:

var div = document.createElement("div");
div.id = "yourID";
var divText = document.createTextNode("Whatever");
div.appendChild(divText);
document.body.appendChild(div);

So in terms of your html code, it would be

<html>
        <body>
            <script>
                var div = document.createElement("div");
                div.id = "yourID";
                var divText = document.createTextNode("Whatever");
                div.appendChild(divText);
                document.body.appendChild(div);
                div.addEventListener("click", function(el) {
                    alert("clicked the created element with id: " + el.target.id);
                }, false);
            </script>
        </body>
    </html>

Comments