How do I clone a single part of content from a h3-element?
Good morning everybody!
I hope you can help me simplifying my code-snippet. I'm cloning a h3-element with all its content. This cloned element contains two a-elements and three different text snippets. I want to remove the a-elements and part1 and part2 of the content being some static text. They only text I want to hold is textOfUnknownLength.
Problem 1 I have to use the jQuery-li开发者_JS百科brary from version 2.6. This is my code I got so far and it's ugly. I just couldn't figure out another way.
The cloned h3-element
<h3 class="title">
part1 <a href="#" class="link1">text</a>
part2 textOfUnknownLength
<a href="#" class="link2">text</a>
</h3>
My code to get the textOfUnknownLength
var name = $("h3",e).clone();
name.find(".link1, .link2").remove();
name.filter("h3").each(function(){
if($(this).html() != ''){
$(this).html($(this).html().replace('part1','').replace('part2',''));
}
});
Problem 2 I want to replace h3 with span, but hold the content. How would I do this?
Thank you for your help.
To replace all h3
s with span
s you could use this:
$( "h3" ).each( function( index, element ) {
var $element = $( element );
$element.replaceWith( "<span>" + $element.html() + "</span>" );
} );
EDIT: I edited the code to work with your jQuery Version (< 1.4)
EDIT 2: I edited the code to REALLY work with your jQuery Version (< 1.4)
Try something like this...
Demo: http://jsfiddle.net/bZ8px/1
var name = $('.title').text().split(' ');
for (var i = 0; i < name.length; i++) {
if (name[i] == 'part2')
$('.title').after('<span>'+name[i+1]+'</span>');
}
If your goal is to turn
<h3 class="title">
part1 <a href="#" class="link1">text</a>
part2 textOfUnknownLength
<a href="#" class="link2">text</a>
</h3>
into
<span>textOfUnknownLength</span>
Check out: http://jsfiddle.net/h6DKe/8/
精彩评论