Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print out jQuery object as HTML

Tags:

Is there a good way of printing out a jQuery object as pure HTML?

ex:

<img src="example.jpg">  <script> var img = $('img').eq(0); console.log(img.toString()); </script> 

toString() doesn't work this way. I need the HTML equivalent string , i.e:

<img src="example.jpg">

like image 610
David Hellsing Avatar asked Dec 07 '09 11:12

David Hellsing


People also ask

How to print the value of an object in jQuery?

In order to print value of objects in JQuery you can create a new array with values and print it: var array = $.map (object, function (value) { return value; })

How to include HTML tags in string output using jQuery?

From jQuery 1.6+ you can just use outerHTML to include the HTML tags in your string output: .outerHTML didn't work for me, but .prop ('outerHTML') did. jQuery.fn.goodOLauterHTML= function () { return $ ('<a></a>').append ( this.clone () ).html (); } I was also using this but this doesn't seem to work for Firefox 6.0.1.

How to display JSON object data in HTML?

The response had HTTP status code 400 You may want to use JSONP or something else. There are options for that discussed here. You will need an iterator to display your json object data in html. In jQuery you can use $.each or in plain javascript you can use a for-in loop. $.each (data, function (i, val) { $ ('div').append (val.test); });

How do I create an element based on an existing page?

Create an element e.g. div or label inside the html body with a specific attribute e.g.class,id,name You can use other attributes of elements to fetch them by class,name or html tag type. Show activity on this post. But that ain't going to be too pretty and will override the existing page content.


2 Answers

$('img')[0].outerHTML

will give you the HTML of the first img on the page. You will then need to use a for loop to get the HTML of all the images, or put an ID on the image and specify it only in the jQuery selector.

like image 196
bmarti44 Avatar answered Sep 25 '22 13:09

bmarti44


You could wrap it and then use html:

var img = $('img').eq(0); console.log(img.wrap("<span></span>").parent().html()); 
like image 39
Magnar Avatar answered Sep 24 '22 13:09

Magnar