• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 330
  • Last Modified:

jQuery: First image in var

I want the first image of var h to be alerted.  For example, there should be an alert with the following:
<img src="1" alt="1" />
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Website</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>

</head>
<body>

<h1>I want the first image of var h to be alerted.</h1>


<script type="text/javascript">
/*<![CDATA[*/

var h = '<img src="1" alt="1" /><img src="2" alt="2" /><img src="3" alt="3" />';

alert( $(h).first() );
alert( 'Should alert <img src="1" alt="1" />' );

/*]]>*/
</script>

</body>
</html>

Open in new window

0
hankknight
Asked:
hankknight
  • 2
2 Solutions
 
hieloCommented:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Website</title>

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
// http://yelotofu.com/2008/08/jquery-outerhtml/
jQuery.fn.outerHTML = function(s) {
return (s) ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html();
}

$(function(){
	var h = '<img src="1" alt="1" /><img src="2" alt="2" /><img src="3" alt="3" />';
	alert( $('img:eq(0)', $('<p>').append(h)).outerHTML() );
});


</script>
</head>
<body>

<h1>I want the first image of var h to be alerted.</h1>




</body>
</html>

Open in new window

0
 
HainKurtSr. System AnalystCommented:
use

alert("<" + h.split("<")[1]);
0
 
HainKurtSr. System AnalystCommented:
or this

alert(h.split(">")[0]+">");
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now