0

I was wondering whether there is a good way of attaining the following: I select a HTML class, marked with a certain CSS class (say <span class="myclass">My content</span>) and I want the browser to render it as the text "My content" customized in some weird ways, for instance in this way: I write

<span class="myclass" data-image="myimage.jpg" data-title="My Title">My content</span>

and I get it replaced with

<h1>My Title</h2> My con<img src="myimage.jpg">en<img src="myimage.jpg">

(one occurrence of the image for each 't'.

I mean, I would like some Javascript code to be executed with arguments the inner HTML and the attributes of my <span class="myclass"> tags; this code should have the effect of replacing my HTML tag with some more complicated HTML code, but keeping it in exactly the same position in the HTML page. Is it possible to do it?

Sorry for my awful way of posing the question, but I am an autodidact in HTML and Javascript!

3
  • By what criteria should this system know which letters to remove and where to place the image(s)? Commented Oct 12, 2013 at 16:25
  • I seem to have been to slow, since you already accepted an answer. I was working on an example and thought I would share it with you anyway: jsfiddle.net/CNWNt Let me know if you want me to post an answer and explain the code Commented Oct 12, 2013 at 16:46
  • The example is alright, thank you. I suppose the code goes in the heading of the document, am I correct? Commented Oct 12, 2013 at 16:51

1 Answer 1

1

If you want to repalce the HTML rather than the text content, you can always use the replaceWith() function:

var newContnet = '<h1>My Title</h2> My con<img src="myimage.jpg">en<img src="myimage.jpg">';

$( ".myClass" ).replaceWith(newContent);

And here is a super-simple example:

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function(){
          var newContnet = '<h1>My Title</h2> My con<img src="myimage.jpg">en<img src="myimage.jpg">';
          $(".myClass").replaceWith(newContnet);
        });
        </script>
    </head>
    <body>
        <span class="myclass" data-image="myimage.jpg" data-title="My Title">My content</span>
    </body>
</html>
Sign up to request clarification or add additional context in comments.

2 Comments

I think this is quite what I was looking for... but where can I get a brief tutorial for learning it? (for instance, to understand where to put the code, how to do the queries etc.?
There are lots of sites where you can learn jquery. Read them first and try some coding. Then come back with a specific coding question.

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.