Reputation: 290
For example, I have
var element = "<input type=\"number\" id=\"anElement\">"
I want to retrieve the id
I am trying this code :
var newvalueFonts = element.attr('id').val();
and it is not working. Why?
Am I doing it worng or I just have to fix code little bit
Upvotes: 0
Views: 41
Reputation: 31
After doing var element = "" you need to attach the element into the DOM using $("#divid").append(element) (divid is the id into which we need to put the input element). After that you can use
var newvalueFonts = $("input[type=number]").attr('id');
Upvotes: 2
Reputation: 15555
var element = "<input type=\"number\" id=\"anElement\">"
var newvalueFonts = $(element).attr('id')
console.log(newvalueFonts)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$()
.val()
to get .attr()
Upvotes: 1
Reputation: 133403
You can create a jQuery object using the string, then use various methods on it.
var newvalueFonts = $(element).attr('id');
var element = "<input type=\"number\" id=\"anElement\">";
var newvalueFonts = $(element).attr('id');
console.log(newvalueFonts)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1
Reputation: 337560
You can put that string in a jQuery object, then call prop()
on it to get the id
:
var element = '<input type="number" id="anElement">';
var newvalueFonts = $(element).prop('id');
console.log(newvalueFonts);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
For your reference your original code (var newvalueFonts = element.attr('id').val();
) doesn't work as element
is a string, so there is no attr()
method on it. Even if it was, attr()
itself returns a string which also has no val()
method.
Upvotes: 1