0

I'm trying to convert jQuery:

$li = $(this);
$li.prepend('<span class="icon-"></span>');

function to VanillaJS using createElement.

li = document.createElement('span');

But still this statement does not do what prepend function does. Can you please suggest any better solution.

supun94
  • 123
  • 7
  • You can see how it's done in the jQuery source: https://j11y.io/jquery/#v=1.11.2&fn=jQuery.fn.prepend - `insertBefore()` – Rory McCrossan Aug 17 '17 at 15:57
  • http://callmenick.com/post/prepend-child-javascript – yaakov Aug 17 '17 at 15:59
  • You can still use HTML for this instead of `createElement`. Use [`.insertAdjacentHTML()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML) like this.. `li.insertAdjacentHTML("beforebegin", "")` – spanky Aug 21 '17 at 20:33
  • @spanky since `$li` represent `$(this)` seems we can't use `insertAdjacentHTML` here. Got a 'TypeError' when do the execution. So any better option instead of using `insertAdjacentHTML` ? – supun94 Aug 22 '17 at 05:17
  • So don't use jQuery. `this.insertAdjacentHTML(...)` Your question is asking for Vanilla JS so you just use the DOM element that `this` points to directly. – spanky Aug 22 '17 at 11:29
  • @spanky `this.insertAdjacentHTML(...)`not worked and got the following error msg `Uncaught TypeError: this.insertAdjacentHTML is not a function`. Seems need to replace `HTMLElement` instead of using `this`. Could you please let me know any better way to do this. – supun94 Aug 22 '17 at 12:32
  • If `this` is an element, which it seems to be, it should work. Check for typos. Here's a demo: https://jsfiddle.net/5epmetrh/ – spanky Aug 22 '17 at 12:36
  • Thank you @spanky. Yes it works perfect and did some changes in `this` element . – supun94 Aug 22 '17 at 13:48
  • Very good. Glad it worked. – spanky Aug 22 '17 at 13:51

0 Answers0