Evan
Evan

Reputation: 3501

Append HTML to Node using jquery

The HTML below displays the date and time within the same DATE class. This is no good, because I want to style them independently. But I can't as is, so I thought jquery could be injected to split it up.

<div class="container">
    <a class="title" href="http://www.example.com">Headlines Goes Here</a>
    <div class="date">Jan 29, 2013 12:05:00 PM EST</div>
    <div class="post">
        <p>Content Goes Here</p>
    </div>
</div>

I'm hoping with someone's help this could be solved with jquery by appending within the DATE class so the output would look like this:

<div class="container">
    <a class="title" href="http://www.example.com">Headlines Goes Here</a>
    <div class="date">Jan 29, 2013</div><div class="time">12:05:00 PM EST</div>
    <div class="post">
        <p>Content Goes Here</p>
    </div>
</div>

This is my JQUERY so far, which I styled as red so I could see a physcal change, can someone help solve this issue? my jquery is clearly not correct.

$(window).load(function(){
         if ($(".date:contains(', 2013')").length)
             this.parentNode.append(this).html("</div><div class=time style=color:red>");
});

This is my fiddle: http://jsfiddle.net/3ZWkQ/

Upvotes: 1

Views: 67

Answers (2)

Pablo Romeo
Pablo Romeo

Reputation: 11396

Ideally you would want to do this server-side, to avoid having to alter the actual document structure.

But if that is not possible, you can do it the following way:

$(function() {
  $(".date").after(function() {
    var val = $(this).text();
    var justDate = val.substring(0,12);
    $(this).text(justDate);
    var parsedTime = val.substring(12);
    return "<div class=time >" + parsedTime + "</div>";
  });
});

NOTE: Here I just used substring for the splitting, but that obviously won't be the correct implementation, you're better off parsing to a Date and formatting the parts using a jquery plugin, prototype, etc.

Here's the fiddle: http://jsfiddle.net/MS3W6/

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Change this part:

this.parentNode.append(this).html("</div><div class=time style=color:red>")

To:

$(this.parentNode).append("<div class=time style=color:red></div>")

Upvotes: 0

Related Questions