Add another class to a div

前端 未结 7 911
盖世英雄少女心
盖世英雄少女心 2020-11-29 07:29

I have a function that checks the age of a form submission and then returns new content in a div depending on their age. Right now I am just using getElementById to replace

相关标签:
7条回答
  • 2020-11-29 07:30

    In the DOM, the class of an element is just each class separated by a space. You would just need to implement the parsing logic to insert / remove the classes as necesary.

    I wonder though... why wouldn't you want to use jQuery? It makes this kind of problem trivially easy.

    0 讨论(0)
  • 2020-11-29 07:39

    Well you just need to use document.getElementById('hello').setAttribute('class', 'someclass');.

    Also innerHTML can lead to unexpected results! Consider the following;

    var myParag = document.createElement('p');
    
    if(under certain age)
    {
        myParag.text="Good Bye";
        createCookie('age', 'not13', 0);
        return false;
    {
    else
    {
        myParag.text="Hello";
        return true;
    }
    
    document.getElementById('hello').appendChild(myParag);
    
    0 讨论(0)
  • 2020-11-29 07:41

    If the element has no class, give it one. Otherwise, append a space followed by the new className:

      var el = document.getElementById('hello');
      if(el) {
        el.className += el.className ? ' someClass' : 'someClass';
      }
    
    0 讨论(0)
  • 2020-11-29 07:43

    I am facing the same issue. If parent element is hidden then after showing the element chosen drop down are not showing. This is not a perfect solution but it solved my issue. After showing the element you can use following code.

    function onshowelement() { $('.chosen').chosen('destroy'); $(".chosen").chosen({ width: '100%' }); }
    
    0 讨论(0)
  • 2020-11-29 07:47

    I use below function to animate UiKit gear icon using Just JavaScript

    document.getElementById("spin_it").onmouseover=function(e){
    var el = document.getElementById("spin_it");
    var Classes = el.className;
    var NewClass = Classes+" uk-icon-spin";
    el.className = NewClass;
    console.log(e);
    }
    <span class="uk-icon uk-icon-small uk-icon-gear" id="spin_it"></span>

    This code not work here...you must add UIKit Style to it

    0 讨论(0)
  • 2020-11-29 07:48

    Use Element.classList

    document.getElementById('hello').classList.add('someClass');
    

    The .add method will only add the class if it doesn't already exist on the element. So no need to worry about duplicate class names.

    0 讨论(0)
提交回复
热议问题