Home > database >  Javascript Variable Not Changing Value With Html Content Changing
Javascript Variable Not Changing Value With Html Content Changing

Time:04-23

I have a code that im trying to make a variable that changes if the price of the product changes hers the code:

<h3 ><span ><span >5000</span></h3>

var price_aft = document.querySelector("#app > main > div > div > div.container > div > div.product-details > div.product-section.price-section > h3 > span.after.currency-value > span.value").textContent

when the price changes the variable value does not change? can someone help me please! thank you.

CodePudding user response:

The HTML is malformed. So, I'm not sure you mean:

A:

<h3 >
  <span >
    <span >5000</span>
  </span>
</h3>

or B:

<h3 >
  <span ></span>
  <span >5000</span>
</h3>

So, I went with option A:

let selector = ".single-price .after .value";
let priceAft = document.querySelector(selector);
console.log(priceAft.innerHTML);
<h3 >
  <span >
    <span >5000</span>
  </span>
</h3>

CodePudding user response:

WOW, that's an enormous selector chain,

first of all, make sure your selector is correct, you can remove .textContent from the end of your js code and see if querySelector can find your element (use console.log to see what is stored in your variable)

then if the variable has undefined value, your selector is wrong if the element was selected correctly, try out innerText instead of textContent and let me know of the result

CodePudding user response:

  // select span
  var target = document.getElementById('value');
var currValue = '';

// create observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log("event trigger "   mutation.target.id);
  });
});

// pass what to listen
var config = {
  attributes: true,
  childList: true,
  characterData: true
};

// pass span node and config
observer.observe(target, config);

// simulate the Change of the text value of span
function onValueChange() {
  currValue = target.textContent;
  console.log(currValue);
}

setTimeout(onValueChange, 2000);
<h3 ><span ><span id="value" >5000</span></h3>

CodePudding user response:

Make suer none of your variables are cons. Then you would need to import the HTML into JavaScript. If this doesn't work, you're more likely to get the code working by looking it up on google.

  • Related