Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using javascript/jQuery to get attribute values from an HTML string

I have an HTML string that contains text and images, e.g.

<p>...</p>
<img src="..." />
<p>...</p>

I need to get the src attribute of the first image. The image may or may not come after a <p> and there could be more than one image, or no image at all.

Initially, I tried appending the string to the DOM and filtering. But, if I do this the browser requests all of the external resources. In my situation, this adds a lot of unnecessary overhead.

My initial approach:

var holder = $('<div></div>'); 

holder.html(content);

var src = holder.find('img:first').attr('src'); 

How can I get the src of the first image without appending the HTML? Do I need to use a regular expression, or is there a better way?

The solution needs to be javascript/jQuery based – I'm not using any server side languages.

My question is very similar to: http://forum.jquery.com/topic/parsing-html-without-retrieving-external-resources

Thanks

like image 607
DB. Avatar asked Sep 14 '10 18:09

DB.


People also ask

How to get for attribute value in jQuery?

The jQuery attr() method is used to get attribute values.

How can we fetch all attributes for an HTML element in Javascript?

To get all of the attributes of a DOM element: Use the getAttributeNames() method to get an array of the element's attribute names. Use the reduce() method to iterate over the array. On each iteration, add a new key/value pair containing the name and value of the attribute.

What is the jQuery method for retrieving the html content of an element?

jQuery html() Method The html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element.

How to pass values in HTML to jQuery?

click(function () { var id = $(this). attr('itemId'); var name = $(this). attr('itemName'); // ... }


1 Answers

This

$("<p><blargh src='whatever.jpg' /></p>").find("blargh:first").attr("src")

returns whatever.jpg so I think you could try

$(content.replace(/<img/gi, "<blargh")).find("blargh:first").attr("src")

Edit

/<img/gi instead of "<img"

like image 108
Dave Aaron Smith Avatar answered Sep 19 '22 08:09

Dave Aaron Smith