Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make this code work without jQuery?

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!

like image 232
SeinopSys Avatar asked Dec 14 '12 22:12

SeinopSys


People also ask

Can I use JavaScript without jQuery?

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.

What can replace jQuery () in a function call?

You can use the function getElementsByTagName() which queries the DOM for elements of a certain tag and returns a collection of elements.

Why jQuery is not needed?

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.


1 Answers

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.

like image 71
I Hate Lazy Avatar answered Oct 19 '22 22:10

I Hate Lazy