1

I have a block of text I would like to change to an ul list. To determine where the text would break I thought I could use a character like / So the text might be.

    <p>
      /Red Car/Green Car/Black Car
    </p>

I need a list like this.

    <ul>
      <li>Red Car</li>
      <li>Green Car</li>
      <li>Black Car</li>
    </ul>

I've been trying to do it like this.

      $(function(){
        var list = '';
        $('.whatWeDo').find('=').each(function(){ //.whatWeDo id the <p>
            list += '<li>' + $(this).next() + '</li>';
        });
        var theList = $('ul').append(list);
        $('.whatWeDo').html(theList);
      })
1
  • 1
    What is the question here? Please edit the post with details about what behavior you are looking for that you aren't seeing, any errors, etc. Commented Feb 6, 2013 at 17:11

2 Answers 2

2

Try this:

var items = $('p').text().trim().split('/');
$('p').replaceWith('<ul>');
for (var i = 0; i < items.length; i++) {
    if(items[i].length >0) $('ul').append('<li>' + items[i] + '</li>');
}

jsFiddle example

Sign up to request clarification or add additional context in comments.

Comments

1

.find() looks for a jQuery selector, not text.

Try this, which pretends that your original element has an id of original:

jQuery(function ($) {

    // Get your original list, and its text
    var $original = $('#original');
    var text = $original.text();

    // Split the text at every '/', putting the results into an array
    var listItems = text.split('/');

    // Set up a new list
    var $list = $('<ul></ul>');

    // Loop through the list array, adding an <li> for each list item
    listItems.each(function(item){
        $list.append('<li>' + item + '</li>');
    });

    // Replace the old element with the new list  
    $original.replaceWith( $list );

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.