Collizo4sky Collizo4sky - 5 months ago 7
Javascript Question

Get the HTML body of a <link> element with an ID via jQuery

I have the following in the header of my site

<link rel="stylesheet" id="swp-google-font-headline-css" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro&ver=4.5.3" type="text/css" media="all">


I want to retrieve the full
<link>
content as shown above with jquery.

I tried

var a = jQuery('#swp-google-font-headline-css').get(0);
console.log(a, typeof a)


But the console output displayed the actual content, but it seem to be an object rather than a string and i specifically want it to be a string.

See demo https://jsfiddle.net/collizo4sky/qh6dnmg9/

Please help

Answer

Use outerHTML property of the Element

The outerHTML attribute of the element DOM interface gets the serialized HTML fragment describing the element including its descendants.

var a = jQuery('#swp-google-font-headline-css').get(0).outerHTML;
console.log(a,typeof a)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" id="swp-google-font-headline-css" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro&ver=4.5.3" type="text/css" media="all">ffff