2
<div class="twtr-tweet-text">
    <p>lorem ipsum <em>date 19th nov</em></p>
</div>
<div class="twtr-tweet-text">
    <p>lorem ipsum <em>date 18th nov</em></p>
</div>
<div class="twtr-tweet-text">
    <p>lorem ipsum <em>date 17th nov</em></p>
</div>

How can I transform this block to the code below. Keeping in mind that multiple blocks contain the same class names etc.

<div class="twtr-tweet-text">
    <p><img src="speech_left.jpg" />lorem ipsum <img src="speech_right.jpg" /><em>date 19th nov</em></p>
</div>

So before the <em> starting tag and right after the <p> tag after the .twtr-tweet-text{} class.

2 Answers 2

5
$('.twtr-tweet-text p').prepend('<img src="speech_left.jpg" />');
$('.twtr-tweet-text em').before('<img src="speech_right.jpg" />');
Sign up to request clarification or add additional context in comments.

3 Comments

It won't work, and it does not bring errors, so my CSS call is not working. I though jQuery can do CSS jumps, edit code.
$(document).ready(function () { $('.twtr-tweet-text p').prepend('<img src="/blog/assets/imgs/speech-mark-left.jpg" />'); $('.twtr-tweet-text p em').before('<img src="/blog/assets/imgs/speech-mark-right.jpg" />'); });
How could I do this in NORMAL javaScript?
1

You can use, in addition to Scott's answer:

$('<img src="speech_left.jpg" />').prependTo($('.twtr-tweet-text p'));


Edited to add a plain-JavaScript means of achieving the same:

var elems = document.getElementsByTagName('p'),
    leftImageSrc = 'speech_left.jpg',
    rightImageSrc = 'speech_right.jpg',
    className = 'twtr-tweet-text',
    parent, // used in the loop, below
    img; // used in the loop, below

for (i=0;i<elems.length;i++){
    parent = elems[i].parentNode; // looking at two qualities of the parent,
                                  // so storing it in a variable
    if (parent.tagName.toLowerCase() == 'div' && parent.className == className){
    // the 'if' tests that the parent is a div, and
    // that the parent has a class-name of 'twtr-tweet-text'
        // left image:
        lImg = document.createElement('img');
        lImg.src = leftImageSrc;
        // the firstChild of the elems[i] element is the textNode
        elems[i].insertBefore(lImg,elems[i].firstChild);

        // right image:
        rImg = document.createElement('img');
        rImg.src = rightImageSrc;
        elems[i].appendChild(rImg);
    }
}

JS Fiddle demo.

3 Comments

How could I do Scott Brown and your answer in NORMAL javaScript?
See the edited/updated answer. I'm not sure about IE (unavailable for testing), but it works in Chromium 14 and Firefox 7.
...and this is why I use jQuery :-)

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.