Recover Classname using . Css() from Angularjs

Asked

Viewed 62 times

1

I have a page that displays several divs that when clicked retrieves and displays the attributes used to create them: float, border, width and etc.

I’d like to retrieve the classname, but I’m not getting it.

I use Angularjs 1.2.1.

HTML:

<h2>Clique nas DIV´s para exibir os atributos do CSS</h2>

<div id="box1">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<div id="box4">4</div>
<p class="clear"></p>
<p id="result">&nbsp;</p>

Script:

<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
$("div").click(function () {
    var html = ["<strong>A DIV selecionada possui os seguintes atributos:</strong>"];

    var styleProps = $(this).css(["classname","float", "border",
        "width", "height", "color", "background-color"]);
    $.each(styleProps, function (prop, value) {
        html.push(prop + ": " + value);
    });

    $("#result").html(html.join("<br>"));
});
}//]]>  

</script>

Example running Fiddle

1 answer

2


Jay, className is not a CSS property, but a DOM property (javascript). To access this property, just use the function attr. As follows:

HTML:

<h2>Clique nas DIV´s para exibir os atributos do CSS</h2>

<div id="box1" class="cname">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<div id="box4">4</div>
<p class="clear"></p>
<p id="result">&nbsp;</p>

Script:

$(function(){
    $("div").click(function () {
        var html = ["<strong>A DIV selecionada possui os seguintes atributos:</strong>"];

        var styleProps = $.extend({ classname: $(this).attr('class') || '' }, 
            $(this).css(["float", "border", "width", "height", "color", "background-color"])
        );
        console.log(styleProps);
        $.each(styleProps, function (prop, value) {
            html.push(prop + ": " + value);
        });

        $("#result").html(html.join("<br>"));
    });

    alert($("div").css('classname'));
})

Example running Fiddle

  • Valeu worked correctly, thank you very much. https://jsfiddle.net/jothaz/wgzqrbkm/14/

Browser other questions tagged

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