Reputation: 2110
I would like to add a hyperlink to a page using JS like this:
var TopLink=document.createElement("a");
TopLink.setAttribute("href", "#top");
TopLink.innerHTML = "Top";
TopLink.setAttribute("class", "btn btn-default btn-ref");
TopLink.setAttribute("style", "position:absolute; top:280px; right:40px; width:120px; background:yellow;");
document.body.appendChild(TopLink);
However, I need to update the <body>
tag to have an ID value of top
as it isn't there on the page.
I have tried various things, such as:
// using jQuery
$(document).ready(function(){
$("body").attr('id', 'top');
});
// using vanilla js
var body_tag = getElementsByTagName("body");
body_tag.setAttribute("id", "top");
But neither work - how can I set the ID attribute of the body tag?
I had a look here first: assigning ID's to body tag using jquery
But it didn't answer my question.
Upvotes: 0
Views: 3672
Reputation: 6565
It is not necessary to add the id.
However, if you want to add some to the body with jQuery in Tampermonkey you need some things...
First, include jQuery into your script like e.g.
// @require http://code.jquery.com/jquery-3.4.1.min.js
to use it in your anonymous function, you have to add it like
(function($) {
'use strict';
//source
})(window.jQuery);
Now you can run some things with jQuery. You can create whatever element you want and then append it to the body. In this example, I add a button to Google's body.
// ==UserScript==
// @name Test
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match https://www.google.de/
// @require http://code.jquery.com/jquery-3.4.1.min.js
// @grant none
// ==/UserScript==
(function($) {
'use strict';
let button = $("<button>Test</button>");
button.appendTo('body');
})(window.jQuery);
You actually can copy this and add your own stuff to it.
You may have a look at Tampermonkey's documentation
See @match to add a better URL matching may using wildcard selector
See @require to add more or another script to your script. E.g. jQuery UI
NOTE:
I'm using (function(){...});
which will invoke itself as soon as the browser is interpreting your ECMA-/javascript. I guess on Tampermonkey it's always at the end here. But I'm not 100% sure.
Feel free to use $(document).ready(function(){ ... });
or short $(function(){...});
to make sure that the DOM is ready when running this script.
Upvotes: 0
Reputation: 8162
Another way is that:
document.body.setAttribute("id", "top");
<body></body>
Upvotes: 2
Reputation: 5091
This will work:
document.body.id = 'top';
getElementsByTagName
returns an HTMLCollection, so you cannot call setAttribute
on that. If I'm not mistaken, it needs to be prefixed with document.
too.
I would imagine the jQuery method is failing because you're not using jQuery on the page. Anyway, no need to use jQuery for something so simple.
Upvotes: 2