I'm trying to convert some jQuery into vanilla JavaScript, but this one just stumped me:
$('<span>[<a href="#" id="addlink">Add</a>]</span>')
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 );
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>
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.