Reputation: 11
I am trying to clone a div's contents only if its content matches a third divs content, so far I have got the clone part to work but can't figure out how to check the contents against another div.
$(function(){
var $button = $('.duration').clone();
$('#ewp-div').html($button);
});
I want to clone the contents of ".duration" to "#ewp-div" , but only if the ".duration" contains the same text as a h1 tag?
I have a fiddle with what I have so far..
http://jsfiddle.net/bloodygeese/aqp0adnx/
Upvotes: 1
Views: 99
Reputation: 93631
Use a :contains
selector, or use a filter
. Either will reduce the matches based on the supplied values/rules.
A basic :contains
selector looks like this: http://jsfiddle.net/aqp0adnx/1/
$(function(){
var $button = $('.duration:contains("September")').clone();
$('#ewp-div').html($button);
});
You can obviously drive the contains
value (September) from the contents of your H1 like this using string concatenation to build the selector:
e.g. http://jsfiddle.net/aqp0adnx/2/
$(function(){
var $button = $('.duration:contains("' + $('h1').text() + '")').clone();
$('#ewp-div').html($button);
});
Update based on comment:
If you want to match the whole H1 (like "September 14") then it will already work as-is:
http://jsfiddle.net/aqp0adnx/3/
If you only want to match the first word for instance, separate that out first based on the space character:
http://jsfiddle.net/aqp0adnx/4/
$(function(){
var $button = $('.duration:contains("' + $('h1').text().split(' ')[0] + '")').clone();
$('#ewp-div').html($button);
});
The rules/logic of how you want to match it is up to you. For example an exact match would need to apply a filter
, but that would not seem to be appropriate for your example data
If you want exact matching, or complex rules use filter
with a function. The function is called for each element in turn. If the function returns true the element is kept (else it is discarded).
e.g. This does an exact match instead: http://jsfiddle.net/aqp0adnx/6/
$(function () {
var h1 = $('h1').text();
var $button = $('.duration').filter(function () {
return $(this).text() == h1;
}).clone();
$('#ewp-div').html($button);
});
Upvotes: 4