Snubagaff
Snubagaff

Reputation: 13

How do I set a variable equal to the value of an attribute within a child element?

I am attempting to set a variable equal to the value of the name of a form in the following html.

<div id="someid">
    <form name="somename">
    </form>
</div>

Here I have tried to set var x equal to the name of the form but I don't think I'm going about this correctly.

$(document).ready(function(){
    if($("#someid").length > 0){
         var x = $($("#someid").children("form")).attr("name");
        if(x !== undefined){
            alert(pkmnId);
        }
    }
});

Upvotes: 1

Views: 595

Answers (3)

viveksinghggits
viveksinghggits

Reputation: 680

Here is a working example, only by using javascript

<div id="someid">
    <form name="somename">
    </form>
</div>


<script>
    var x = document.getElementById("someid").children;
    console.log(x[0].name);

</script>

you will be getting somename in the console, store it in a variable

var _y = x[0].name;

Upvotes: 0

mdickin
mdickin

Reputation: 2385

Take more advantage of your selectors

$("#someid form").attr("name")

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68423

Only problem with this line

var x = $($("#someid").children("form")).attr("name");

is that you are passing a jquery object to the jquery method where either a DOM element is expected or a selector is expected.

change is to

var x = $("#someid").children("form").attr("name"); //observe removing extra $ from the beginning.

Upvotes: 0

Related Questions