如何使用jQuery将指定HTML结构修改为目标嵌套格式?
Hey there! Let's figure out how to tweak your HTML exactly as you need it. You want to take the "Since 1940" segment inside your .intro-lead-in span and wrap it in a new <span class="class-name">—here are a few reliable ways to pull this off with jQuery:
Method 1: Simple HTML Replacement (Best for Fixed Text)
If the text "Creating quality Foods, Since 1940" is static and you don’t have to worry about duplicate phrases elsewhere, this quick approach works perfectly:
$('.intro-lead-in span').html(function(index, oldContent) { // Replace the target text with itself wrapped in the new span return oldContent.replace('Since 1940', '<span class="class-name">Since 1940</span>'); });
The html() method accepts a callback that gives you access to the existing content. We just use replace() to swap out the exact text we want to wrap, and jQuery handles updating the DOM automatically.
Method 2: Split and Reconstruct (More Precise)
If you want to avoid accidental replacements (say, if "Since 1940" might appear elsewhere in the span), splitting the text into parts and rebuilding the HTML is safer:
// Grab the parent span element const $targetSpan = $('.intro-lead-in span'); // Get the full text content and split it at the comma + space const textParts = $targetSpan.text().split(', '); // Reconstruct the HTML with the second part wrapped in our new span $targetSpan.html(`${textParts[0]}, <span class="class-name">${textParts[1]}</span>`);
This splits the original text into two segments at ", ", then combines them back with the second segment wrapped in the desired span. No risk of matching unintended text here.
Method 3: Target Text Nodes Directly (For Complex DOM)
If your span has mixed content (like other elements alongside text), you can target the specific text node containing your phrase:
$('.intro-lead-in span').contents().filter(function() { // Only target text nodes (nodeType 3) return this.nodeType === 3; }).each(function() { const text = this.textContent; if (text.includes('Since 1940')) { // Replace the text node with the modified HTML $(this).replaceWith(text.replace('Since 1940', '<span class="class-name">Since 1940</span>')); } });
This method digs into the span's child nodes, finds the text that includes our target phrase, and replaces just that part with the wrapped version. Great for more complex scenarios.
All three methods will get you to your desired HTML structure:
<div class="intro-lead-in"><span>Creating quality Foods,<span class="class-name">Since 1940</span></span></div>
内容的提问来源于stack exchange,提问作者Lokesh

