xiaofo
xiaofo

Reputation: 67

Using 'javascript:' inside html tag

I am developing a web server with node.js. But I got a problem just now. Below code is my HTML code.

<%
  var tagID = 'something';
%>
<a href="..." id="javascript:tagID">...</a>

I know that if I use 'javascript:' inside a HTML tag. then it can execute javascript code. but it did not work when I checked it on my browser.

Or should I use DOM to do this?

Upvotes: 3

Views: 14101

Answers (3)

nick zoum
nick zoum

Reputation: 7325

There are 3 ways to do what you are asking:

  1. Using a single page application like angular, reacts ...

  2. Use your own custom design pattern that will replace whatever you want to replace

var global = this;

global.id1 = 10;
global.id2 = 30;

document.querySelectorAll("*").forEach(function(dom) {
  [...dom.attributes].forEach(function(attr) {
    if (attr.value.startsWith("javascript:")) {
      dom.setAttribute(attr.name, global[attr.value.replace("javascript:", "")]);
    }
  });
});
<div id="javascript:id1">Div 1</div>
<div id="javascript:id2">Div 2</div>

  1. Do the update manually

document.getElementById("1").id = "10";
document.getElementById("2").id = "20";
<div id="1">Div 1</div>
<div id="2">Div 2</div>

If you are creating a big app then I would reccomand using a single page application (though it might take some time getting to know how it works if you are familiar with it).

If you are feeling adventurous or don't want to bother learning or using an SPA you could create your own framework/design pattern.

If the example you have shown is not a common occurence (and you don't expect it to be more common in the future), easiest solution would be to just manually update the dom.

Upvotes: 0

Manjeet Singh
Manjeet Singh

Reputation: 2398

You can use https://www.npmjs.com/package/ejs

// server.js
// load the things we need
var express = require('express');
var app = express();

// set the view engine to ejs
app.set('view engine', 'ejs');

// use res.render to load up an ejs view file

// index page 
app.get('/', function(req, res) {
    res.render('pages/index');
});

// about page 
app.get('/about', function(req, res) {
    res.render('pages/about');
});

app.listen(8080);
console.log('8080 is the magic port');

you can embed javascript like this

<ul>
    <% drinks.forEach(function(drink) { %>
        <li><%= drink.name %> - <%= drink.drunkness %></li>
    <% }); %>
</ul>
<!DOCTYPE html>
<html lang="en">
<head>
    <% include ../partials/head %>
</head>
<body class="container">

<header>
    <% include ../partials/header %>
</header>

<main>
    <div class="jumbotron">
        <h1>This is great</h1>
        <p>Welcome to templating using EJS</p>
    </div>
</main>

<footer>
    <% include ../partials/footer %>
</footer>

</body>
</html>

Upvotes: 0

Rek
Rek

Reputation: 149

You can use javascript: in a href. Like so

<a href="javascript:alert('hello')">Hi</a>

Upvotes: 3

Related Questions