BearDawg12 BearDawg12 - 4 months ago 31
jQuery Question

JQuery - Change attr based on element innerHTML

I'm trying to add schema markup to products across our site, but I want the attr of the div element to change based on what the text is for the innerHTML

HTML:

<div class="badgeIds" itemtype="https://schema.org/ItemAvailability" itemprop="availability">
Online Only
</div>


Here is what I wrote for the Javascript. Is my logic flawed?

var avail = document.find("div.badgeIds");

if (avail.html().trim() == "Preorder") {
avail.attr("itemprop", "availability:Preorder");
} elseif (avail.html().trim() == "Online Only") {
avail.attr("itemprop", "availability:OnlineOnly");
} elseif (avail.html().trim() == "Available In Store Only") {
avail.attr("itemprop", "availability:InStoreOnly");
};

Kld Kld
Answer

var avail = $("div.badgeIds");
var txt = $("div.badgeIds").text().trim();

 

if (txt == "Preorder") {
      avail.attr("itemprop", "availability:Preorder");
} else if (txt == "Online Only") {
      avail.attr("itemprop", "availability:OnlineOnly");
} else if (txt == "Available In Store Only") {
      avail.attr("itemprop", "availability:InStoreOnly");
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 

<div class="badgeIds" itemtype="https://schema.org/ItemAvailability" itemprop="availability">
   Online Only
</div>