Infotheek SE
Infotheek SE

Reputation: 123

Javascript/Jquery - Add script to div with Javascript/Jquery?

I need to add a piece of javascript (Linkedin sharebutton) to a div, but I cant access the DOM directly. I can use Javascript/jquery to alter the DOM though so I was wondering if its possible to append Javascript to a certain div, or even better create a div inside the container and target the script there?

The script:

<script src="//platform.linkedin.com/in.js" type="text/javascript"> lang: en_US</script>

The html:

<div class="left"></div>

Upvotes: 0

Views: 211

Answers (2)

rtf_leg
rtf_leg

Reputation: 1819

Try this code, it creates nested container (as you ask) inside your "left" div and creates script tag inside this container:

$(".left").html(
  $("<div>").html(
    $("<script>").attr({ 
      "type": "text/javascript", 
      "src": "//platform.linkedin.com/in.js"
    })
  )
);

Do not foreget to reference jQuery.

Upvotes: 0

Cosmin
Cosmin

Reputation: 2214

You can use javascript for this.

Example:

var scriptTag= document.createElement( "script" );
scriptTag.type = "text/javascript";
scriptTag.src = "//platform.linkedin.com/in.js";
$(".left").append(script);

Try it

EDIT: To keep it elegant you can use .appendChild, instead of .append

Upvotes: 4

Related Questions