riotgear riotgear - 1 month ago 6
HTML Question

I am having an issue getting jquery to insert html depending on the classname

The problem I am trying to solve.
I want to use jQuery to dynamically add content to a div depending on which class is being used. I am not sure why the alerts aren't working. It could be my html or the jquery itself. I want to solve this so that I can have different text appear depending on which class shows up.

Here is the HTML

<td>
<div class="po size3"></div>
<a class="external">Find your doctor</a>
<div class="p-accessible-alt"></div>
</td>

<td>
<div class="po size4"></div>
<a class="external">Find your doctor</a>
<div class="p-accessible-alt"></div>
</td>

<td>
<div class="po size5"></div>
<a class="external">Find your doctor</a>
<div class="p-accessible-alt"></div>
</td>


Here is the jQuery

$(document).ready(function() {
if ($(this).hasClass("size5")) {
$("div.p-accessible-alt").html("<p> Blah Blah Size5</p>");
} else if
($(this).hasClass("size4")) {
alert('TEST!!!');
$("div.p-accessible-alt").html("<p> Blah Blah Size4</p>");
} else if
($(this).hasClass("size3")) {
alert('TEST 3!!!');
$("div.p-accessible-alt").html("<p> Blah Blah Size3</p>");
}
});

Answer

Your usage of $(this) won't work because you haven't made a selection. In JQuery this is always bound to the context the previous selector or method, it's a JQuery object containing the results of the selection or filter. Additionally, your selector for finding the child element to insert HTML into is too broad.

$("div.p-accessible-alt").html("<p> Blah Blah Size3</p>");

It will select every single <div> with a class of p-accessible-alt and insert the same HTML block into all of them.

You can replace your entire if block with the following selectors (one for each size).

$(".size3").siblings(".p-accessible-alt").html("<p> Blah Blah Size3</p>");
$(".size4").siblings(".p-accessible-alt").html("<p> Blah Blah Size4</p>");
$(".size5").siblings(".p-accessible-alt").html("<p> Blah Blah Size5</p>");

This works by finding the element with the class .sizeX and then traverses up to it's parent container, then back down the hierarchy to find it's descendant with the class .p-accessible-alt and then apply the html to that.

Comments