Ian
Ian

Reputation: 3

jquery append and javascript appendChild not working for html tags period

I started out trying to add meta tags in the <head> tags but now have found that I can't add anything to any html tags. Not <body>, <p>, <h1>, nothing but it works fine with div id's and classes.

Here's the html

    <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="append.js"></script>
<title>appendTest</title>
</head>
<body>

<div id="test">
<p>
Hello World
</p>
</div>

</body>
</html>

And here's the append.js examples I've tried

    function loadmeta(){
var meta = "<meta name='og:title' content='some random content' />";
document.getElementsByTagName('head').item(0).appendChild(meta);
}

window.onload = function(){
loadmeta();
}




/*jquery style*/

$(document).ready(function(){
$('html').append('meta name="testing" content="some content"/>');
});

$(document).ready(function(){
$('meta name="testing" content="some content"/>').appendTo('html');
});

Now I tried the jquery functions both append and appendTo with the p#test for the div and I can append to it with both functions. However I tried with head, body, p and it doesn't work with any of them.

I'm beginning to wonder is there is some kind of security setting on my server that is stopping it because I have used append to append text and css styles and append to the body before and had no problem.

firebug gives no errors and I've tried it in FF and Chrome.

Although I don't want to feel like an idiot I'd love if someone sees some silly mistake I made.

Thanks

Upvotes: 0

Views: 3892

Answers (2)

mplungjan
mplungjan

Reputation: 178011

You are not creating the element correctly

function loadmeta(){
  var meta = document.createElement("meta");
  meta.name='og:title'; // or meta.setAttribute("name","og:title");
  meta.content='some random content';
  document.getElementsByTagName('head')[0].appendChild(meta);
}

However I am not even sure your meta tags will be interpreted after the load of the page

Upvotes: 1

Paul
Paul

Reputation: 141827

None of your codes are correct:

First of all for your javascript only version appendChild expects a node, not a string of HTML.

You could do something like:

var meta = "<meta name='og:title' content='some random content' />";
var head = document.getElementsByTagName('head')[0];
head.innerHTML = meta+head.innerHTML;

You jQUery methods are both missing the opening HTML tag.

Upvotes: 2

Related Questions