sineverba sineverba - 11 months ago 42
jQuery Question

Jquery: append element inside tag and before another one

Let's say I have this HTML

<div id="cpu-temperature">
<p><span class="degrees"> °C</span></p>

I would insert via Jquery the degree inside the P and before the span.

Of sure, I could (as now) write the span via jquery, but I would elaborate from the script only the "raw" number and not the html.

In fact current code is:

$('div#cpu-temperature p').html(cpu_temperature+'<span class="degrees"> °C</span>');

Of course I need to beware also for the problem of "append". The temperature logged every 5 second, so a simple "append" flush the page after some time...


You can use .prepend() to add to the beginning of whatever element was selected.

$('div#cpu-temperature p').prepend(cpu_temperature);

Edit -

Since you want to update only the temperature each time, I would add another element before the degrees span. So you have

<div id="cpu-temperature">
    <p><span class="temp"></span><span class="degrees"> °C</span></p>

And then just run


I don't know if this is really better than what you were already doing, but I don't think you can just clear the contents of the <p> tag without clearing out the child element. At least not easily.