Reputation: 667
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
Upvotes: 0
Views: 92
Reputation: 9
You can use outerHTML.
var b = a.outerHTML;
Demo: https://jsfiddle.net/qh6dnmg9/2/
Upvotes: 0
Reputation: 253318
There are two means by which this can be achieved, the first – as already shown – is to use the Node.outerHTML
property, which in your posted code can by achieved like so:
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/2.1.1/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
And the other approach is more of a shim, and achieved by appending the found-element, here the <a>
, to another element and accessing the innerHTML
of that parent element:
function getElementHTML(node) {
var wrapper = document.createElement('div');
wrapper.appendChild(node);
return wrapper.innerHTML;
}
console.log($('#swp-google-font-headline-css').get(0));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/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
Upvotes: 0
Reputation: 4919
You can use innerHTML
property on your a
variable.
$(document).ready(function() {
var a = $('#swp-google-font-headline-css').get(0);
console.log(a.innerHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/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">
Upvotes: 0
Reputation: 682
Maybe this is what you want:
var a = jQuery('#swp-google-font-headline-css').clone();
console.log(a[0]);
Upvotes: 0
Reputation: 36599
Use outerHTML
property of the Element
The
outerHTML
attribute of the elementDOM
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
Upvotes: 1