Home  >  Q&A  >  body text

javascript - How to dynamically set the attribute class="" using js?

I now want to set an element with <p class=""></p>, but
var p=$('<p></p>').attr({ 'class':""});
The <p class></p> attribute set in this way is empty, and escaping has no effect. Maybe there is something wrong with my writing.
May I ask for a solution? ~

PHP中文网PHP中文网2710 days ago538

reply all(5)I'll reply

  • 習慣沉默

    習慣沉默2017-05-19 10:17:43

    You can use
    .attr('class', null)
    or
    .removeAttr('class')

    reply
    0
  • 怪我咯

    怪我咯2017-05-19 10:17:43

    
    $('body'). append('<p></p>').attr("class", "classname")

    reply
    0
  • 怪我咯

    怪我咯2017-05-19 10:17:43

    var pHtml = "<p>This is a p element</p>";
    $("body").html(pHtml );
    $("p").addClass("\'\'");

    You can try this to see if it is the effect you want.

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-19 10:17:43

    For elements whose attributes are equal to empty strings, the browser will automatically retain only the attributes. What are you planning to do by setting this?

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:17:43

      var p1= $("<p class>haha</p>")
      $("body").append(p)
      $(".addItem").click(function(){
        alert($('p').hasClass(""))  //true
      })

    You get <p class>haha</p> which is equivalent to <p class=''>haha</p>

    reply
    0
  • Cancelreply