简体   繁体   中英

Targeting an element within a created element, Pure JS

I've been developing a snippet of code for a while now mostly using Pure JS I'm not to well versed on JS but I can walk my way around it within reason. I'm trying to target an element of HTML that has been placed inside a JS created div.

The idea is to change the color of a character counter when it gets to 50 then finally 0. I have tried to implement the following snippet myself but I'm having difficulties trying to get it to work correctly.

After some digging around the net I stumbled upon a question located here, Stack Overflow Question . Mentioning the need to dive deeper in sourcing the element thats being targeted Ie var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0]; . However I feel it doesn't really apply to me as I'm not giving my created div an ID or using classes.

Here's what I tried to implement,

 // create wrapper element
  this.wrapper = document.createElement("div");
  this.wrapper.innerHTML = 'Chars left: <span id="int">' + (this.MAX - input.value.length), '</span>';

// The <span></span> element is the one I am trying to adjust.

// check counter value
var tail = document.getElementById("int");

if (this.MAX - this.INPUT.value.length <= 50) {
    tail.style.color = "#ffa";
} else if (this.MAX - this.INPUT.value.length <= 0) {
    tail.style.color = "#f00";
}

You can find the full code snippet I've been creating using JSFiddle . Can anyone help me identify what I am missing here, or enlighten me as to if I'm approaching this wrong?

Looks like you need to listen for when a character is entered into the input. Those .value.length properties aren't updated live, so you'll need to check every time the user presses a key.

// create wrapper element
this.wrapper = document.createElement("div");
this.wrapper.innerHTML = 'Chars left: <span id="int">' + (this.MAX - input.value.length), '</span>';

// check counter value
var tail = document.getElementById("int");

// Inside the event handler function, the "this" keyword changes meaning to mean the element on which the event listener is attached. Redefining the variable here is one way to get max inside the handler.
var max = this.MAX;

this.INPUT.addEventListener('keyup', function () {
    if (max - this.value.length <= 50) {
        tail.style.color = "#ffa";
    } else if (max - this.value.length <= 0) {
        tail.style.color = "#f00";
    }
}

You might also want to check the logic of else if (max - this.value.length <= 0) - the length will never be less then zero :) Also, what do you want to happen when it goes above 50?

在此样式化:

TextAreaRanger.prototype["update"] = function() {.....}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM