Reputation: 3384
I'm trying to convert some jQuery into vanilla JavaScript, but this one just stumped me:
$('<span>[<a href="#" id="addlink">Add</a>]</span>')
Upvotes: 1
Views: 65
Reputation: 8118
The Vanilla Javascript approach for the same could also be achieved using setAttribute()
, createTextNode()
and appendChild()
as follows. Just another way to do this.
const span = document.createElement("span");
const a = document.createElement("a");
a.setAttribute("href", "#");
a.setAttribute("id", "addlink");
const text = document.createTextNode("Add");
a.appendChild(text);
span.append("[", a, "]");
document.body.appendChild(span);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<script src="./script.js"></script>
</body>
</html>
Upvotes: 0
Reputation: 136986
It's not a selector, it creates the DOM elements from this markup and wraps it in a jQuery object. See the docs.
const $el = $('<span>[<a href="#" id="addlink">Add</a>]</span>');
console.log( $el.html() );
$("body").append( $el );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
So the vanilla equivalent would be
const span = document.createElement("span");
const a = document.createElement("a");
a.href = "#";
a.id = "addlink";
a.textContent = "Add";
span.append( "[", a, "]" );
document.body.append( span );
Upvotes: 2