Javascript To Change Metadata / Metatags Dynamically

前端 未结 5 673
小蘑菇
小蘑菇 2020-12-19 15:21

I\'ll describe what I\'m trying to accomplish and if it seems that my method is dumb please feel free to let me know:

I have a page with a video gallery and a flash

相关标签:
5条回答
  • 2020-12-19 15:33

    @bernabas's answer in plain ol' JavaScript:

    document.head.textContext += '<meta ... />'

    0 讨论(0)
  • 2020-12-19 15:39

    You wanna do something like this in the code for jQuery

    $(document).ready(function(){
        $('title').text("Your new title tag here");
        $('meta[name=description]').attr('content', 'new Meta Description here');
    });
    
    0 讨论(0)
  • 2020-12-19 15:43

    Shorter answer in pure javascript.

    document
          .getElementsByTagName('meta')
          .namedItem('description')
          .setAttribute('content','My Meta Description Here')
    
    0 讨论(0)
  • 2020-12-19 15:44

    you can add anything in the head tag by using the this (jquery)

    $('head').append('<meta .... />');
    
    0 讨论(0)
  • 2020-12-19 15:57

    As the above two solutions are using JQuery, here is a solution in pure javascript, incase if anyone is looking for:

    to change the title:

    <script>document.title = "this is title text";</script>
    

    to change any meta tag:

    <meta name="description" content="this is old content which we are going to change through javascript">
    

    javascript code to change the above metatag.

    <script>
    var allMetaElements = document.getElementsByTagName('meta');
    //loop through and find the element you want
    for (var i=0; i<allMetaElements.length; i++) { 
      if (allMetaElements[i].getAttribute("name") == "Description") { 
         //make necessary changes
         allMetaElements[i].setAttribute('content', "description you want to include"); 
         //no need to continue loop after making changes.
         break;
      } 
    } 
    

    Good luck.

    0 讨论(0)
提交回复
热议问题