jQuery inserting html as text instead of DOM object

221
December 07, 2017, at 06:02 AM

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);
                              })
    });
Answer 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>

READ ALSO
variable dosent set new value [duplicate]

variable dosent set new value [duplicate]

This question already has an answer here:

177
Using JavaScript to change were a link is pointing to based on screen size

Using JavaScript to change were a link is pointing to based on screen size

I am creating a mobile-first site using the Bootstrap 4 frameworkI am trying to create a JavaScript function which will change where a <a> tag is pointing to based upon the screen size of the browser

188
How to add an event outside the Slick after clicking on the dot marker

How to add an event outside the Slick after clicking on the dot marker

I use a standard slider slider, and I want to add an event outside the slider itself but on the same pageI tried to catch the event in different ways:

118