Jarrod Jarrod - 3 months ago 9
Javascript Question

How do I loop through divs and find the nearest span and add different things to each span?

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)


  1. Go to each
    <div>
    with the class 'div-style'

  2. Find the following
    <span>

  3. Append the current
    <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')


Answer

$('.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