I would just like a mapping of some of the jQuery methods to their normal Javascript DOM methods;
e.g.
prev()
next()
before()
after()
It would be really great if you could provide mapping of jQuery/Javascript to similar DOM manipulation methods.
None of these jQuery methods have an exact 1-to-1 analogue in plain DOM-based JS. If they did, there would be no need for jQuery to implement its own methods to accomplish these tasks.
You can get previous and next siblings for an element using elem.previousSibling and elem.nextSibling. For example, with this HTML structure:
<ul>
<li>First</li>
<li id="second">Second</li>
</ul>
You'd use this JS:
var elem = document.getElementById("second");
var p = elem.previousSibling;
alert(p.nodeType);
In this case, the previous sibling of the second LI is not the first LI. Instead, the previous sibling is the empty white space between the two LI tags. This was done so that you can manipulate any text node in the document in addition to actual HTML elements. The nextSibling property works identically.
That's nice in theory, but it's more or less a pain in the neck in actual usage, because you rarely or never are actually going to need to manipulate the whitespace in a document. To work around, iterate through the siblings checking the nodeType. If the nodeType is 1, then it's a text node, so skip to the next one till you find one whose nodeType isn't 1.
You may find the blog post Finding HTML elements using Javascript nextSibling and previousSibling helpful. Just avoid the technique of extending Object.prototype he uses -- it's very easy to break for/in loops over objects by doing that.
As for before() and after(), the DOM equivalent is insertBefore() and insertBefore() run on the sibling AFTER the target you want. However, you can't just throw some HTML into those and expect it to work. Instead you have to manually create each element, attribute, and value as DOM nodes, and then insert them. For example:
var welcomingDiv;
function sayHi(){
welcomingDiv = document.createElement("div");
welcomingDiv.innerHTML = "Welcome, and be amazed!";
target = document.getElementById("a-tag-someplace");
document.body.insertBefore(welcomingDiv, target);
}
That will insert it into your document right before whatever tag has the ID "a-tag-someplace". Even this is kind of a cheat though, since innerHTML is not part of the official JS standard. IF you were doing it properly, you'd have to create a text node and append it to your newly created DIV.
So, in short: jQuery makes life a lot simpler. Don't reinvent the wheel without a really good reason.
prev() - previousSibling, its a property
next() - nextSibling, its a property
before() - insertBefore,
after() - There is no insertAfter method but we implement it using insertBefore
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