For example say I had the following HTML:
<div class="div-style">div text</div> <span>span text</span>
<div class="div-style">another div</div> <span>another span</span>
<div class="div-style">hello</div> <span>world</span>
Now what I want to do is: (using jQuery)
<div>
with the class 'div-style' <span>
<span>
's text to the span (in effect repeating the span text within the span text, so the first span would display 'span textspan text') Here you go: https://jsfiddle.net/rg9zanks/
$('.div-style + span').each(function() {
var span = $(this)
span.after('<span>' + span.text() + '</span>')
})
You can take advantage of the +
selector to avoid using the .next()
function.
.div-style
.each()
, create a new span after the selected spans using after()
, and populate it with the same text using .text()
. Literally a one-liner with jQuery, a little something like this:
$(".div-style + span").html(function(i,v) { return v + v; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="div-style">div text</div> <span>span text</span> <div class="div-style">another div</div> <span>another span</span> <div class="div-style">hello</div> <span>world</span>
Further reading:
+
next sibling selector .html()
method (or you could use the .text()
method instead) $('.div-style').each(function(){ var t = $(this).next('span').text(); $(this).next('span').text($(this).next('span').text() + t); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="div-style">div text</div> <span>span text</span> <div class="div-style">another div</div> <span>another span</span> <div class="div-style">hello</div> <span>world</span>
Try this
$('.div-style').each(function(i, node){ var nextSpan = $(node).next(); nextSpan.append(nextSpan.html()); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="div-style">div text</div> <span>span text</span> <div class="div-style">another div</div> <span>another span</span> <div class="div-style">hello</div> <span>world</span>
$(function () {
$("div.div-style").next('span').each(function () {
$(this).append($(this).text());
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.