Search code examples
javascriptjqueryjquery-selectors

Cannot append image with jquery


I currently have a code working where i can add a class based on the url of a page using jquery. However I would like add an image to a div instead of just adding a class. I'm not as proficient in java-script as I could be but I think there is probably a pretty simple solution. The code that doesn't work is

if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
        var img = document.createElement("img");
        img.src = '~/Content/Images/Template 5A Filmstrip.jpg" />';



    }

the code that works right now that I dont want to use is

if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
        var $body = $('body');

        $body.addClass('campaign');


    }

How can apply what I do know that works to what I am trying to get to work?


Solution

  • If for some reason you don't want to use jQuery for this part, you just need to append the element to the body of the html document (or wherever you want it to end up) like so:

    Javascript Code

    if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
      var body = document.getElementsByTagName("BODY")[0];
      var img = document.createElement("img");
      img.className = 'img-responsive'
      img.src = '~/Content/Images/Template 5A Filmstrip.jpg';
      body.appendChild(img);
    }