JQuery Issue HTML not inserting


#1
<script>
	$(window).bind("load", function() {
		$( document ).ready(function() {
	    if($('p').hasClass('para2')) {
	      $('p').html('<img src="http://html.trafficopedia.com/songsite/img/folder.svg" width="50" height="25" alt="">');
	    }
	});
	});
	</script>

Reference WP site here.

I am trying when the paragraph has the class para2 it should insert an HTML. The final output will be like this:

<p class="para para2">
   <img src="http://html.trafficopedia.com/songsite/img/folder.svg" width="50" height="25" alt="">Content from WP Editor
</p>

But This is not happening for now.


#2

okay. Lets start with the basics.

#1: Selectors.

Instead of doing this, let’s just select the elements you want to change. You want to change p elements that have the class “para2”. In CSS terms, that is defined as “p.para2” (note the lack of spaces. That’s important. If we’d said “p .para2” , it would read as “Select all elements with class para2 inside p elements.”)

jQuery can take any valid CSS selector. So, in jQuery terms:
$('p.para2')
selects all of the elements we want to modify.

#2: Timing
We dont need to bind to window onload, a document ready. We can skip the outer bit entirely, and just say:

		$( document ).ready(function() {
	      $('p.para2').html('<img src="http://html.trafficopedia.com/songsite/img/folder.svg" width="50" height="25" alt="">');
	    });

#3: Even cleaner!
jQuery has a shorthand for the document ready declaration. Odd as it looks: $(<function>); So we can make it cleaner:

$(function() {
	      $('p.para2').html('<img src="http://html.trafficopedia.com/songsite/img/folder.svg" width="50" height="25" alt="">');
	    });

#4: The Wordpress downside.
Wordpress and jQuery dont quite play nicely. WP overrides jquery’s default $ declaration and requires you to use “jQuery” everywhere you have $'s. We can fix that, with this somewhat odd syntax:

(function($) {
  // do all your $ based jquery in here.
  $(function() {
	      $('p.para2').html('<img src="http://html.trafficopedia.com/songsite/img/folder.svg" width="50" height="25" alt="">');
  });
})(jQuery);

#3

It worked, but I have done a little bit of modification.

<script>
	(function($) {
		// do all your $ based jquery in here.
		$(function() {
		  $('p.para2').prepend('<img src="http://html.trafficopedia.com/songsite/img/folder.svg" width="50" height="25" alt="">');
		});
	})(jQuery);
</script>

I changed HTML with Prepend HTML was eliminating all the content coming from the the_content() - The WP loop.


#4

That falls under a logical issue, rather than a procedural one - I made your code work, you’re responsible for what you tell it to do :wink:


#5

Yes, Yes. Right.