Question

I am trying to get a line of JQuery script to read every paragraph string found in a div and split that paragraph every time there is a ','. My issues is that I am unable to POST all of the array at once, so the replaceWith function only outputs the first value of the array because the rest of the array is deleted when the for condition returns to increment to myArray[1].

Is there anyway for me to post every value in the 'array of splits' to separate html elements without leaving the initial string and/or turning every created element a child of the previous element?

DEMO http://jsfiddle.net/ry25Q/

HTML

    <div class="data">
        <i>days_of_week</i>
        <p>mon,tue,wed,thur,fri,sat,sun</p>
    </div>
      <div>
        <input type="button" class="btnClick Button" value="Click" />
     </div>

JS CODE

$(function () {
    $('.btnClick').click(function () {
        var data = $('.data p').text();
        var splitter = data.split(',');
        for (var i = 0; i < splitter.length; i++) {
            $(".data p").replaceWith("<span class='dataseg'>" + splitter[i] + "</span>")
        }
    });
});
Was it helpful?

Solution

You don't need a loop. Since you're only replacing one p element, just call .replaceWith() once with the full HTML string you're inserting.

DEMO: http://jsfiddle.net/Vfk4e/

$(function () {
    $('.btnClick').click(function () {
        var p = $('.data p');
        var splitter = p.text().split(',');

        var open = "<span class='dataseg'>";
        var close = "</span>"

        p.replaceWith(open + splitter.join(close + open) + close)
    });
});

OTHER TIPS

Can't you just add $('.data p').text(''); before your for statement? This will clear the contents,t hen your .append from your fiddle will work just fine.

$(function () {
    $('.btnClick').click(function () {
        var data = $('.data p').text();
        var splitter = data.split(',');

        $('.data p').text('');

        for (var i = 0; i < splitter.length; i++) {
            $(".data p").append("<span class='dataseg'>" + splitter[i] + "</span>")
        }
    });
});

Try to create a variable for the span element you wish to replace the <p> element with. Then inside of your for loop, sequentially add your data to the span element. After the loop, close your span and then call replaceWith() with the span variable.

$(function () {
    $('.btnClick').click(function () {
        var data = $('.data p').text();
        var splitter = data.split(',');
        var daySpan = "<span class='dataseg'>";

        for (var i = 0; i < splitter.length; i++) {
            daySpan += splitter[i]; 
        }

        daySpan += "</span>";

        $(".data p").replaceWith( daySpan );
    });
});

Demo: http://codepen.io/imajedi4ever/pen/kpzCD/?editors=101

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top