0

I'm trying to insert a DOM element using jQuery but it keeps being inserted as text instead.

var newImg = "<h1>Hi</h1>";
    $("li").each(function myFn(){
        this.addEventListener("mouseover", function myFn2 () {
                             this.before(newImg);
                              })
    });
2
  • Side note, the each is unnecessary. $('li').on('mouseover', function () { ... }); would perform the same function Commented Dec 6, 2017 at 19:48
  • ah ok, ill tidy that up too, thanks Commented Dec 6, 2017 at 19:56

1 Answer 1

1

If you console.log(this) you should find that it is not a jQuery object inside the event handler. You will want to wrap it with $() before you use the before method to use the jQuery method.

$(this).before(newImg);

var newImg = "<h1>Hi</h1>";
$("li").each(function myFn() {
  this.addEventListener("mouseover", function myFn2() {
    $(this).before(newImg);
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Wee</li>
</ul>

Sign up to request clarification or add additional context in comments.

2 Comments

That does make it an object, but it displays on the page as [object Object] now
The code snippet in the answer doesn't insert [object Object] so something you are doing is different.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.