Get `Meta` attribute `content` by selecting `property` attribute

后端 未结 3 1471
灰色年华
灰色年华 2021-01-05 05:14

In jQuery you can do this:

$(\"meta[property=\'fb:app_id\']\").attr(\"content\");

Which will give you the content attribute va

相关标签:
3条回答
  • 2021-01-05 05:26
    document.querySelector('meta[property~="fb:app_id"][content]').content
    
    0 讨论(0)
  • 2021-01-05 05:40

    Not as elegant as JQuery I'm afraid...

    var metaTags=document.getElementsByTagName("meta");
    
    var fbAppIdContent = "";
    for (var i = 0; i < metaTags.length; i++) {
        if (metaTags[i].getAttribute("property") == "fb:app_id") {
            fbAppIdContent = metaTags[i].getAttribute("content");
            break;
        }
    }
    
    console.log(fbAppIdContent);
    
    0 讨论(0)
  • 2021-01-05 05:42

    Note: Some use the property attribute:

    <meta property="fb:app_id" content="1234567890">
    

    whereas others use the name attribute:

     <meta name="fb:app_id" content="1234567890">
    

    I use the following to get the value from both variants:

    var appId = (function(c) { for (var a = document.getElementsByTagName("meta"), b = 0;b < a.length;b++) {
      if (c == a[b].name || c == a[b].getAttribute("property")) { return a[b].content; } } return false;
    })("fb:app_id");
    
    console.log(appId); //(bool)false if meta tag "fb:app_id" not exists.
    


    The same can be used for every other meta tag as well - just change the input value on the closure function (eg. from fb:app_id to description).
    Edit: Or as a more generic function:

    function getContentByMetaTagName(c) {
      for (var b = document.getElementsByTagName("meta"), a = 0; a < b.length; a++) {
        if (c == b[a].name || c == b[a].getAttribute("property")) { return b[a].content; }
      } return false;
    }
    
    console.log(getContentByMetaTagName("og:title"));
    
    0 讨论(0)
提交回复
热议问题