Currently I have a code that looks like this:
$('a.guide-item[href="/"]').remove();
$('*[href="/"]').attr('href','/feed/subscriptions/u');
I need to make the file size smaller, but I don't know how to replicate the code in "vanilla" javascript. Please help!
Don't get me wrong - jQuery is still a wonderful library and most often than not you will be better off using it. However, for smaller things like simple pages with limited JS interactions, browser extensions and mobile sites, you can use vanilla JS.
You can use the function getElementsByTagName() which queries the DOM for elements of a certain tag and returns a collection of elements.
DOM manipulation was not straight forward, thanks to jQuery developers can manipulate with little effort. Today all browsers in use today support document. querySelectorAll, which accepts a CSS selector and returns a list of matching nodes. In many ways thanks to jQuery, jQuery itself is no longer needed.
Without supporting IE6/7, it's very simple.
var els = document.querySelectorAll('a.guide-item[href="/"]');
for (var i = 0; i < els.length; i++) {
if (els[i].parentNode)
els[i].parentNode.removeChild(els[i]);
}
els = document.querySelectorAll('*[href="/"]');
for (i = 0; i < els.length; i++) {
els[i].setAttribute('href','/feed/subscriptions/u');
}
If you need to support IE6/7, it's still very simple, but it would be helpful to have a method that selects elements by class, or at least that tests for a class.
Not hard to find implementations of these on the web.
Here's a quick implementation that will support older IE.
var els = document.links,
i = els.length;
while (i--) {
if (els[i].getAttribute("href") !== "/")
continue;
if (els[i].className.indexOf("guide-item") !== -1) {
els[i].parentNode.removeChild(els[i]);
} else {
els[i].setAttribute('href','/feed/subscriptions/u');
}
}
It assumes that the .className
won't have other classes where "guide-item"
would be matched as a sub-pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With