0

I have a textarea that contains several images. All images have an id and I want to loop through all of those images and check if the need an onclick event (depends on id) If the do not need a onclick event I need to check if the have one and remove it. If the need I I still need to remove it and add another (because the value of the onclick could be changed)

How can I do this?

<img id="slideShowImage_3" style="border: 1px solid black; cursor: pointer;" title="3" onclick="loadSlideShow('7','open','3','','2')" src="uploads/nieuws/7/1363788115.jpg" alt="3" />
<img id="slideShowImage_3" style="border: 1px solid black; cursor: pointer;" title="3" src="uploads/nieuws/7/1363788115.jpg" alt="3" />

http://jsfiddle.net/wmrqk/4/

3
  • 5
    Your textarea contains images ? You mean the HTML of images elements ? Commented Mar 21, 2013 at 13:29
  • 1
    You have two images with the same id; that's strictly not allowed. Commented Mar 21, 2013 at 13:37
  • It's an text editor, and the 2 images in my example are the same 1 with and 1 without onclick Commented Mar 21, 2013 at 13:53

3 Answers 3

1

Try this:

function cleanCode() {
    var container = $('<div>' + $('#text1').val() + '</div>');
    container.find('img').removeAttr('onclick');
    $('#text2').html(container.html());
}

Demo

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

1 Comment

thanks, I like the idea of putting the content in a div, this should give me all the jquery options
1

May not be cool, but you can do something like

function cleanCode() {
    var els = $($('#text1').val());
    els.each(function(i, v){
        var $this = $(this);
        if($this.attr('id') == 'slideShowImage_1'){
            $this.removeAttr('onclick')
        }
    });
    console.log($('<div></div>').append(els).html())
}

Demo: Fiddle

Comments

1

For a very simple HTML like the one you have here you could do this :

$('#text2').html($('#text1').html().replace(/onclick="[^"]*"/g,''));

But be very careful : parsing HTML in regex fails in general cases so you can only do that if you know where your HTML comes from and what it is like.

If your HTML is well formed, you can also do this :

var e = $('<div>'+$('#text1').val()+'</div>');
e.find('img').attr('onclick','');
$('#text2').html(e.html());

Demonstration

In any case, be aware that this couldn't be used as a security measure.

1 Comment

thanks, I like the idea of putting the content in a div, this should give me all the jquery options

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.