MaryCoding
MaryCoding

Reputation: 664

Get value of element found inside another element(multiple classes)

I am currently trying to retrieve the value of an input field of class anotherClass through jquery selectors. However I get an empty result. Below is different methods I used to get this value but to no avail I get the desired result. There are many input fields with that class but what makes the input unique is the label wrapped around it. How could I retrieve the result of the input field shown below?

HTML

<label class="class1 class2 class3" data-reactid=".0.1">
    <input class="anotherClass" type="text" data-reactid=".0.1.0" value="XXXXXXX" >
</label>

Jquery

function getValue() {
    var element = document.querySelectorAll('.class1 .class2 .class3 input');
    return Array.prototype.map.call(element, function(e) {
        return e.getAttribute('value');
    });
}

Upvotes: 1

Views: 87

Answers (3)

Adil
Adil

Reputation: 148110

You do not need space between classes as space mean you are going for descendant. You can combine multiple class with dot or comma.

 var element = document.querySelectorAll('.class1.class2.class3 input');

Or using comma

 var element = document.querySelectorAll('.class1,class2,class3 input');

Upvotes: 2

AmmarCSE
AmmarCSE

Reputation: 30557

With your html above, it should be as simple as

$('.anotherClass').val();

If you want to search from the parent, using their classes, you can do

$('.class1.class2.class3 .anotherClass').val();

document.write($('.class1.class2.class3 .anotherClass').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<label class="class1 class2 class3" data-reactid=".0.1">
  <input class="anotherClass" type="text" data-reactid=".0.1.0" value="XXXXXXX">
</label>

Upvotes: 0

Ted
Ted

Reputation: 14927

Think of your selectors the same way you would as if you were writing CSS:

var element = $('.class1.class2.class3 input');

Upvotes: 1

Related Questions