Created
October 10, 2012 05:52
-
-
Save garethredfern/3863401 to your computer and use it in GitHub Desktop.
Using jQuery to append & prepend existing content to somewhere else in the DOM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Adding Content To The DOM</title> | |
<style> | |
article { width: 600px; margin: 0 auto; } | |
blockquote { | |
width: 30%; | |
float: right; | |
font-size: 2em; | |
text-align: center; | |
background-color: #eee; | |
} | |
</style> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> | |
</head> | |
<body> | |
<article> | |
<h1>Article One</h1> | |
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod | |
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, | |
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo | |
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse | |
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non | |
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> | |
<p><span class="co">This is the quote of the week</span>, consectetur adipisicing elit, sed do eiusmod | |
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, | |
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo | |
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse | |
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non | |
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> | |
<p><span class="co">This is the quote of the week</span>, consectetur adipisicing elit, sed do eiusmod | |
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, | |
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo | |
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse | |
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non | |
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> | |
</article> | |
<script> | |
(function() { | |
// use a function on the filtered elements to set the new content. | |
$('article').find('span.co').each(function() { | |
var $this = $(this);//store 'this' in a var to cache it. | |
//use an object to set the new text. | |
$('<blockquote></blockquote>', { | |
class: 'co', | |
text: $this.text() | |
}).prependTo( $this.closest('p') ); | |
}); | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment