简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM