My goal is to utilize jQuery for looping through classes and adding text to an HTML element. I am currently working with the following example HTML:
<div class="question">
<div class="title">
<strong>Here's the question title.</strong>
</div>
<div class="choice">Here's choice1.</div>
<div class="choice">Here's choice2.</div>
</div>
<div class="question">
<div class="title">
<strong>Here's the question title.</strong>
</div>
<div class="choice">Here's choice1.</div>
<div class="choice">Here's choice2.</div>
</div>
I am trying to loop through each question on the page, check if the title matches a specific string, and then append some text accordingly. Here is my current code snippet:
$('.question').each(function() {
var title = $(this).find('.title').text();
$('.choice').each(function() {
var span = document.createElement("span");
if (title == "someString")
{
span.className = "someClass";
}
else
{
span.className = "someOtherClass";
}
var text = document.createTextNode("text");
span.appendChild(text);
$(this).append(span);
});
document.body.style.backgroundColor = "orange"; // to test the outer loop
});
The text should change color based on the title, hence the different CSS classes. However, nothing seems to be happening - the text is not being appended to each choice. The background color does change to orange, and there are no errors in Chrome developer tools. Any assistance would be greatly appreciated.