skij
asked on
jQuery: Perform action on first match without using each()
Using jQuery, how can I perform this action only on the first item without using each()? Is there a way I can just use [0]?
<!DOCTYPE html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('button').on("click", loadImage);
});
function loadImage() {
$('#fake-elem-container').contents().filter(function() {
return this.nodeType == 8;
}).each(function(i, e) {
$('#container').append(e.nodeValue);
});
}
</script>
</head>
<body>
<button>Load the Content!</button>
<br><br>
<div id="fake-elem-container">
<!--
1
-->
<!--
2
-->
<!--
3
-->
</div>
<div id="container"></div>
</body>
</html>
http://jsfiddle.net/wgf5yrz8/
ASKER
Is there a simple way to do this without foreach?
Yes
Try this
Try this
function loadImage() {
var fakeValue = $('#fake-elem-container').contents().filter(function() {
return this.nodeType == 8;
})[0];
$('#container').append(fakeValue);
}
ASKER
Thanks, but it isn't working for me. Am I doing something wrong?
<!DOCTYPE html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('button').on("click", loadImage);
});
function loadImage() {
var fakeValue = $('#fake-elem-container').contents().filter(function() {
return this.nodeType == 8;
})[0];
$('#container').append(fakeValue);
}
</script>
</head>
<body>
<button>Load the Content!</button>
<br><br>
<div id="fake-elem-container">
<!--
1
-->
<!--
2
-->
<!--
3
-->
</div>
<div id="container"></div>
</body>
</html>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Great, thanks!
You are welcome.
Can do but clumsy
Open in new window
BetterOpen in new window
In your case it is more tricky because you are using a filter. I would just do a return false from the .each() this has the same effectOpen in new window