Search code examples
javascriptjquerymeta

If Meta exists get value and insert text into a div html?


I have a global header that external applications include without the ability to modify.

The do have access to add a meta tag. And I want to check if they add a meta tag with title and if it exists take value and insert into an h2 empty div.

HTML

The meta tag would look like this:

<meta name="HeadTitle" id="HeadTitle" content="This Apps Title"/>

Markup will look like this:

 <div id="optionalTitle" class="col-md-5 col-md-offset-4 pull-right"><h2></h2></div>

JavaScript

How do I check if a meta name exists and if so, get the value and insert it into the h2 element?

  if ($('#HeadTitle').length) {
    // append content to optionalTitle h2
  }

Update Progress

I have it working like this

    if ($('#HeadTitle').length) {
            $('#optionalTitle > h2').append($('#HeadTitle').prop('content'));
     }  

but not like this

     var $meta = ($('#HeadTitle'));
       if ($meta.length) {
            $('#optionalTitle > h2').append($meta.prop('content'));
        }  

enter image description here


Solution

  • You're on the right track. Just use the .append() method on the appropriate element:

    var $meta = $('#HeadTitle');
    if ($meta.length) {
        $('#optionalTitle > h2').append($meta.prop('content'));
    }
    

    If you wish to replace the content instead of appending, .text() would work better for you.