Search code examples
jqueryattributesmeta

Inverting Meta attributes on jQuery


I'm trying to invert meta attributes (content and name) by using a jQuery function but ONLY if the meta content starts with "some"

<meta name="abc" content="something"/>
<meta name="def" content="somewhere" />

I've tried this function :

<script>
$('meta').ready(function(){
var a_metaname = $(this).attr("name");
var a_metacontent = $(this).attr("content");

if(a_metacontent^="some") {
$('head').append("<meta name="+ a_metacontent +" content="+ a_metaname +" />");

}
 });
</script>

but it doesn't invert the couple name/content for each meta.

How could I improve the function ? Thanks !


Solution

  • $('meta').ready(function(){
    

    Here you are probably confusing two things: $('meta').each(...) will iterate over all meta tags. $(document).ready(...) waits for the ready event. $('meta').ready(...) will probably not do what you think.

    Since the stript tag is, I assume, placed after the meta tags, you don't need to wait for the ready event. Not sure if you can modify the meta tags after the initial load (most of them take effect sooner, as far as I know). Thus, I reccomend not waiting.

    $('meta').each(function(){
    

    if(a_metacontent^="some") {
    

    Unlike in CSS, ^= does not mean "starts with" in Javascript. Instead, ^= performs a bitwise XOR (after converting both operands to an integer) and assigns the result back. You can use indexOf for the "starts with" functionality, or you can use a regex.

    if(/^some/.test(a_metacontent)){
    

    $('head').append("<meta name="+ a_metacontent +" content="+ a_metaname +" />");
    

    You keep the original meta tag in the document, as well as adding the new one. Perhaps you should remove it. Alternatively, instead of creating HTML for the browser to parse, manipulate the existing node. Parsing HTML is slow.

    $(this).attr("content", a_metaname).attr("name", a_metacontent)
    

    Also note that

    $('meta').each(function(){
        if(/^some/.test($(this).attr("content"))) {
            ...
        }
    }
    

    can be replaced with

    $('meta[content^="some"]').each(function(){
        ...
    })