Find class of a dynamically created element

Asked

Viewed 131 times

1

Called the Nav Priority, a lib that places the execendent items within a new drop-down, called "More" this dropdown is dynamically created in pure javascript as soon as it is needed. In it appears a button with the class js-Nav-toggle. I am experiencing some things, and I would like to change some things on this button, with pure javascript, I am doing a test trying to find the class js-Nav-toggle which is definitely in the document, but only gives indefinite.

https://codepen.io/johnquimera/pen/qKLpPe

I use this code that works well on other elements that are written manually from the document. const list = document.getElementsByClassName("js-nav-toggle"); list.style.backgroundColor = "red";

what could be going on?

  • Strange, because I opened the console on the codepen page you passed, I can access it and touch the css of it.

  • @Leandro You managed to change the css of the button with the class "js-Nav-toggle" dynamically with pure javascript?

  • It’s actually not, it was by the console’s same ccs, which is strange, because the class exists. You would have to take a look at the documentation to see how this element is created.

2 answers

1


The variable list is a list of us of the class .js-nav-toggle:

const list = document.getElementsByClassName("js-nav-toggle");

You cannot change the list at once. You need to iterate each element of the list, and you can do this for:

for(let x=0; x<list.length; x++){
   list[x].style.backgroundColor = "red";
}

But if it’s only 1 element, you can use the index [0]:

list[0].style.backgroundColor = "red";

You can also use the querySelector (if only 1 element) or querySelectorAll (1 or more):

document.querySelector(".js-nav-toggle");

Already the querySelectorAll also creates a list of us also to getElementsByClassName, and if it is only 1 element, you also use the index [0]:

const list = document.querySelectorAll(".js-nav-toggle")[0];
list.style.backgroundColor = "red";

Or:

const list = document.querySelectorAll(".js-nav-toggle");
list[0].style.backgroundColor = "red";

However, if it is only 1 element, it makes more sense to use the querySelector:

const list = document.querySelector(".js-nav-toggle");
list.style.backgroundColor = "red";

If it is only 1 element, it makes no sense to create a list of nodes.

Example:

"remove"in Element.prototype||(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)}),!function(){"use strict";var t,e,i,n,r=window,o=document,s=Object,a=null,h=!0,l=!1,d=" ",u="Element",f="create"+u,p="DOMTokenList",c="__defineGetter__",m="defineProperty",g="class",v="List",b=g+v,w="rel",y=w+v,C="div",A="length",x="contains",F="apply",L="HTML",T=("item "+x+" add remove toggle toString toLocaleString").split(d),S=T[2],I=T[3],z=T[4],H="prototype",N=m in s||c in s[H]||a,j=function(t,e,i,n){s[m]?s[m](t,e,{configurable:l===N?h:!!n,get:i}):t[c](e,i)},W=function(e,i){var n=this,r=[],o={},a=0,u=0,f=function(){if(a>=u)for(;a>u;++u)(function(t){j(n,t,function(){return p(),r[t]},l)})(u)},p=function(){var t,n,s=arguments,l=/\s+/;if(s[A])for(n=0;n<s[A];++n)if(l.test(s[n]))throw t=new SyntaxError('String "'+s[n]+'" '+x+" an invalid character"),t.code=5,t.name="InvalidCharacterError",t;for(r=(""+e[i]).replace(/^\s+|\s+$/g,"").split(l),""===r[0]&&(r=[]),o={},n=0;n<r[A];++n)o[r[n]]=h;a=r[A],f()};return p(),j(n,A,function(){return p(),a}),n[T[6]]=n[T[5]]=function(){return p(),r.join(d)},n.item=function(t){return p(),r[t]},n[x]=function(t){return p(),!!o[t]},n[S]=function(){p[F](n,t=arguments);for(var t,s,l=0,u=t[A];u>l;++l)s=t[l],o[s]||(r.push(s),o[s]=h);a!==r[A]&&(a=r[A]>>>0,e[i]=r.join(d),f())},n[I]=function(){p[F](n,t=arguments);for(var t,s={},l=0,u=[];l<t[A];++l)s[t[l]]=h,delete o[t[l]];for(l=0;l<r[A];++l)s[r[l]]||u.push(r[l]);r=u,a=u[A]>>>0,e[i]=r.join(d),f()},n[z]=function(e,i){return p[F](n,[e]),t!==i?i?(n[S](e),h):(n[I](e),l):o[e]?(n[I](e),l):(n[S](e),h)},function(t,e){if(e)for(var i=0;7>i;++i)e(t,T[i],{enumerable:l})}(n,s[m]),n},q=function(t,e,i){j(t[H],e,function(){var t,n=this,r=c+m+e;if(n[r])return t;if(n[r]=h,l===N){for(var s,a=q.mirror=q.mirror||o[f](C),d=a.childNodes,u=d[A],p=0;u>p;++p)if(d[p]._R===n){s=d[p];break}s||(s=a.appendChild(o[f](C))),t=W.call(s,n,i)}else t=new W(n,i);return j(n,e,function(){return t}),delete n[r],t},h)};if(r[p])e=o[f](C)[b],H=r[p][H],e[S][F](e,T),2>e[A]&&(i=H[S],n=H[I],H[S]=function(){for(var t=0,e=arguments;t<e[A];++t)i.call(this,e[t])},H[I]=function(){for(var t=0,e=arguments;t<e[A];++t)n.call(this,e[t])}),e[z](v,l)&&(H[z]=function(e,i){var n=this;return n[(i=t===i?!n[x](e):i)?S:I](e),!!i});else{if(N)try{j({},"support")}catch(V){N=l}W.polyfill=h,r[p]=W,q(r[u],b,g+"Name"),q(r[L+"Link"+u],y,w),q(r[L+"Anchor"+u],y,w),q(r[L+"Area"+u],y,w)}}(),Date.now||(Date.now=function(){return(new Date).getTime()}),function(){"use strict";for(var t=["webkit","moz"],e=0;e<t.length&&!window.requestAnimationFrame;++e){var i=t[e];window.requestAnimationFrame=window[i+"RequestAnimationFrame"],window.cancelAnimationFrame=window[i+"CancelAnimationFrame"]||window[i+"CancelRequestAnimationFrame"]}if(/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent)||!window.requestAnimationFrame||!window.cancelAnimationFrame){var n=0;window.requestAnimationFrame=function(t){var e=Date.now(),i=Math.max(n+16,e);return setTimeout(function(){t(n=i)},i-e)},window.cancelAnimationFrame=clearTimeout}}(),function(t,e,i){"use strict";function n(t,e,n,o){n=n||"width";var a,h,l,f=(e.match(d)||[])[2],p="px"===f?1:u[f+"toPx"],c=/r?em/i;if(p||c.test(f)&&!o)t=p?t:"rem"===f?s:"fontSize"===n?t.parentNode||t:t,p=p||parseFloat(r(t,"fontSize")),l=parseFloat(e)*p;else{a=t.style,h=a[n];try{a[n]=e}catch(m){return 0}l=a[n]?parseFloat(r(t,n)):0,a[n]=h!==i?h:null}return l}function r(t,e){var i,o,s,a=/^top|bottom/,u=["paddingTop","paddingBottom","borderTop","borderBottom"],f,p,c=4;if(i=h?h(t)[e]:(o=t.style["pixel"+e.charAt(0).toUpperCase()+e.slice(1)])?o+"px":"fontSize"===e?n(t,"1em","left",1)+"px":t.currentStyle[e],s=(i.match(d)||[])[2],"%"===s&&l)if(a.test(e)){for(f=(p=t.parentNode||t).offsetHeight;c--;)f-=parseFloat(r(p,u[c]));i=parseFloat(i)/100*f+"px"}else i=n(t,i);else("auto"===i||s&&"px"!==s)&&h?i=0:s&&"px"!==s&&!h&&(i=n(t,i)+"px");return i}var o=e.createElement("test"),s=e.documentElement,a=e.defaultView,h=a&&a.getComputedStyle,l,d=/^(-?[\d+\.\-]+)([a-z]+|%)$/i,u={},f=[1/25.4,1/2.54,1/72,1/6],p=["mm","cm","pt","pc","in","mozmm"],c=6;for(s.appendChild(o),h&&(o.style.marginTop="1%",l="1%"===h(o).marginTop);c--;)u[p[c]+"toPx"]=f[c]?f[c]*u.inToPx:n(o,"1"+p[c]);s.removeChild(o),o=i,t.Length={toPx:n}}(this,this.document);var gn={};gn.optimizedResize=function(){function t(){r||(r=!0,window.requestAnimationFrame?window.requestAnimationFrame(e):setTimeout(e,66))}function e(){n.forEach(function(t){t()}),r=!1}function i(t){t&&n.push(t)}var n=[],r=!1;return{add:function(e){n.length||window.addEventListener("resize",t),i(e)}}}(),gn.getOuterWidth=function(t){var e=/\d/,i=t.offsetWidth,n=t.currentStyle||getComputedStyle(t),r=null===e.exec(n.marginLeft)?"0px":n.marginLeft,o=null===e.exec(n.marginRight)?"0px":n.marginRight;return i+=parseInt(Length.toPx(t,r))+parseInt(Length.toPx(t,o))},gn.getOuterHeight=function(t){var e=/\d/,i=t.offsetHeight,n=t.currentStyle||getComputedStyle(t),r=null===e.exec(n.marginTop)?"0px":n.marginTop,o=null===e.exec(n.marginBottom)?"0px":n.marginBottom;return i+=parseInt(Length.toPx(t,r))+parseInt(Length.toPx(t,o))},gn.isNodeList=function(t){return"undefined"!=typeof t.item},gn.append=function(t,e){var i=gn.isNodeList(t)?t:[t],n;if("undefined"!=typeof e.nodeType&&1===e.nodeType)for(n=i.length;n--;)i[n].appendChild(e);else if("string"==typeof e)for(n=i.length;n--;)i[n].insertAdjacentHTML("beforeend",e);else if(gn.isNodeList(e)){var r=document.createDocumentFragment();for(n=e.length;n--;)r.insertBefore(e[n],r.firstChild);for(var o=i.length;o--;)i[o].appendChild(r)}},gn.prepend=function(t,e){var i=gn.isNodeList(t)?t:[t],n;if("undefined"!=typeof e.nodeType&&1===e.nodeType)for(n=i.length;n--;)i[n].insertBefore(e,i[n].firstChild);else if("string"==typeof e)for(n=i.length;n--;)i[n].insertAdjacentHTML("afterbegin",e);else if(gn.isNodeList(e)){var r=document.createDocumentFragment();for(n=e.length;n--;)r.insertBefore(e[n],r.firstChild);for(var o=i.length;o--;)i[o].insertBefore(r,i[o].firstChild)}},gn.extend=function(){for(var t,e,i,n=arguments[0]||{},r=1,o=arguments.length;o>r;r++)if(null!==(t=arguments[r]))for(e in t)i=t[e],n!==i&&void 0!==i&&(n[e]=i);return n};/**
  * priorityNav native (works with go-native)
  * 
  * v0.1.0
  * @author William Lin
  * @license The MIT License (MIT)
  * https://github.com/ganlanyuan/priorityNav
  */
var priorityNav=function(){"use strict";function t(t){t=gn.extend({nav:".priority-nav",button:"more",showAll:0,hideAll:0},t||{});var i=document.querySelectorAll(t.nav),n=[];if(0!==i.length){for(var r=i.length;r--;){var o=t;o.nav=i[r];var s=new e(o);n.unshift(s)}return n}}function e(t){this.nav=t.nav,this.visibleContainer=this.nav.querySelector("ul"),this.visibleItems=this.visibleContainer.children,this.fragment=document.createDocumentFragment(),this.buttonContent=t.button,this.showAll=t.showAll,this.hideAll=t.hideAll,this.bp=[],this.bpV=[],this.bpH=[],this.initialized=!1,this.nav.classList.add("js-priority-nav"),this.getBreakpoints(),this.updateNav();var e=this;gn.optimizedResize.add(function(){e.updateNav()})}return e.prototype={init:function(){this.nav.querySelector("ul").classList.add("js-nav-visible"),gn.prepend(this.nav,'<button class="js-nav-toggle" data-count="">'+this.buttonContent+"</button>"),gn.append(this.nav,'<ul class="js-nav-hidden is-hidden"></ul>'),this.hiddenContainer=this.nav.querySelector(".js-nav-hidden"),this.hiddenItems=this.hiddenContainer.children,this.btn=this.nav.querySelector(".js-nav-toggle"),this.btnWidth=gn.getOuterWidth(this.btn);var t=this;this.btn.addEventListener("click",function(){t.hiddenContainer.classList.toggle("is-hidden")}),this.initialized=!0},destory:function(){if(this.initialized){if(this.bpH.length>0){for(;this.bpH.length>0;)this.appendItemsToFragment();this.visibleContainer.appendChild(this.fragment)}this.nav.classList.remove("js-priority-nav"),this.visibleContainer.classList.remove("js-nav-visible"),this.hiddenContainer.remove(),this.btn.remove(),this.initialized=!1}},getBreakpoints:function(){for(var t=!1,e=this.visibleItems.length;e--;){t&&(this.visibleItems[e+1].style.display="none");var i=gn.getOuterWidth(this.visibleContainer)+1;this.bp.unshift(i),this.bpV.unshift(i),t=!0}for(var n=0,r=this.visibleItems.length;r>n;n++)this.visibleItems[n].style.display=""},prependItemsToFragment:function(){gn.prepend(this.fragment,this.visibleItems[this.bpV.length-1]),this.bpH.unshift(this.bpV[this.bpV.length-1]),this.bpV.splice(-1,1)},appendItemsToFragment:function(){gn.append(this.fragment,this.hiddenItems[0]),this.bpV.push(this.bpH[0]),this.bpH.shift()},updateNav:function(){if(this.windowWidth=window.innerWidth,this.outerWidth=gn.getOuterWidth(this.nav),this.outerWidth>=this.bp[this.bp.length-1]||this.windowWidth<this.showAll)this.destory();else{if(this.initialized||this.init(),this.availableSpace=this.outerWidth-this.btnWidth,0===this.hideAll||this.windowWidth>=this.hideAll)if(this.availableSpace<=this.bpV[this.bpV.length-1]){for(;this.availableSpace<=this.bpV[this.bpV.length-1];)this.prependItemsToFragment();this.hiddenContainer.insertBefore(this.fragment,this.hiddenContainer.firstChild)}else{for(this.hiddenItems=this.hiddenContainer.children;this.availableSpace>this.bpH[0];)this.appendItemsToFragment();this.visibleContainer.appendChild(this.fragment)}else{if(this.bpH.length===this.bp.length)return;for(;this.bpV.length>0;)this.prependItemsToFragment();this.hiddenContainer.insertBefore(this.fragment,this.hiddenContainer.firstChild)}this.currentCount=this.currentCount||0,this.count=this.bpH.length||0,this.count!==this.currentCount&&(this.currentCount=this.btn.getAttribute("data-count"),this.btn.setAttribute("data-count",this.count))}}},t}();
    priorityNav({
        nav: '.nav',
        hideAll: 300,
    });

  const list = document.getElementsByClassName("js-nav-toggle");
list[0].style.backgroundColor = "red";
@keyframes example {
    from {transform: scale(1);}
    to {transform: scale(1.2);}
}

html {
        font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
    }

    a {
        color: inherit;
        text-decoration: none;
    }

    a:hover {
        text-decoration: underline;
    }

    .link {
        text-decoration: none;
        color: #0fa5f0;
    }

    .link:hover {
        text-decoration: underline;
    }

    .container {
        max-width: 800px;
        margin: 0px auto;
    }

    ul {
        padding: 0;
        margin: 0;
    }

    li {
        list-style: none;
    }

    .priority-nav {
        min-height: 37px;
        background-color: #0E8FE0;
        color: #fff;
        font-size: 14px;
        font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
    }

    .priority-nav li {
        padding: 10px 13px;
    }

    .priority-nav button {
        padding: 10px;
        border-width: 0;
        color: #fff;
        font-size: 11px;
        text-transform: uppercase;
        background-color: #333;
        position: relative;
        overflow: visible;
    }

    .priority-nav button:before {
        content: attr(data-count);
        width: 23px;
        height: 23px;
        line-height: 23px;
        border-radius: 50%;
        font-size: 14px;
        text-align: center;
        position: absolute;
        left: 0;
        top: 50%;
        margin-left: -11px;
        margin-top: -11px;
        color: #412F08;
        background-color: #FFB822;
    
        animation: example 1s infinite;
    }

    .priority-nav .js-nav-hidden {
        background-color: #333;
        z-index: 3;
    }

    .nav-main-wrapper {
      display: table;
    }

    .nav-module {
      display: table-cell;
    }

    .nav-module.nav-main {
      width: 100%;
    }
    
    .priority-nav{position:relative}.priority-nav:after{content:'';clear:both;display:table}.priority-nav>ul{max-width:100%;overflow-x:auto}.priority-nav>ul>li{display:table-cell;white-space:nowrap}.priority-nav .is-hidden{visibility:hidden}.priority-nav.js-priority-nav ul{float:left;max-width:none;overflow-x:hidden}.priority-nav .js-nav-hidden{position:absolute;right:0;top:100%}.priority-nav .js-nav-hidden>li{display:list-item}.priority-nav .js-nav-toggle{position:absolute;right:0;height:100%;cursor:pointer}

/*# sourceMappingURL=priority-nav.css.map */
<div class="container">

   
          <div class="nav priority-nav">
              <ul class="links">
                  <li><a href="">Entertainment</a></li>
                
                  <li><a href="">Sports</a></li>
                  <li><a href="">Business</a></li>
                  <li><a href="">Technology</a></li>
                  <li><a href="">Nation</a></li>
                  <li><a href="">Politics</a></li>
                  <li><a href="">World</a></li>
                  <li><a href="">Opinion</a></li>
                  <li><a href="">Obituaries</a></li>
                  <li><a href="">Travel</a></li>
                  <li><a href="">Life & Style</a></li>
                  <li><a href="">Science</a></li>
              </ul>
          </div>



    </div>

  • It wasn’t. Null. All this works with any element that is already in the document, but for some reason is not working with elements created dynamically.

  • Boy... I modified the ex on the code pen, it works, I don’t understand why it’s not working here on the localhost. https://codepen.io/johnquimera/pen/qKLpPe will conflict with jquery... I will test.

  • 1

    lack of attention from me. I was putting the const list above the call priorityNav now was.

  • I was going to ask another question that has to do with this. You know the button "More", that yellow Bullet that shows the item count. I would like to put a sort of "Pulse" effect on the button when a new item is added. I will remove the counter.

  • no, only when a new item is added.

  • By "all the time" do you mean always visible? As you may have seen this Bullet is done with a pseudo selector, and it is easy to remove it, no, it will not always be pulsing, the pulse will only occur when the window is resized and a new menu item is added. Whenever windows is resized in live time, the amount of items are counted and added to Bullet. It is in this scheme that the pulse must occur. &#xA;.priority-nav button:before {&#xA; content: attr(data-count); /*bullet*/&#xA;}&#xA;

  • That is, whenever visible.

  • yes, it can be, I’ll see how it looks. I think it can be a good.

  • I added in response.

  • Opa very good. perfect. Vlw.

Show 5 more comments

0

Hi @John,

You want to change the color of the class Priority Nav, this?

Via css you can do:

.priority-nav{
  background-color:red!important;
}

or

If you can use jquery, try it this way:

$(".priority-nav").css({
   backgroundColor:'red'
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.