Reputation: 12568
I have a variable in jQuery that looks like this...
var myvariable = '<iframe id="myiframe" class="thisiframe">';
I am trying to extract the id from this so looking to get 'myiframe'
What is the best way of doing this, should I be using regex or is there a jQuery function that would be better to use?
Or can I target the iframe directly using this variable?
Upvotes: 1
Views: 255
Reputation: 207
If format is going to be same then you can simply try this. This would work in this condition.
Note: This is not a proper solution, however, would work fine in this case
myvariable.substr(myvariable.indexOf('id="')+4,(myvariable.indexOf('" '))-myvariable.indexOf('id="')-4)
Upvotes: 1
Reputation: 95
Try once:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var myvariable = '<iframe id="myiframesss" class="thisiframe">';
alert($(myvariable).attr('id'));
});
</script>
Upvotes: 1
Reputation: 1089
To be honest, you can do this is native Javascript as well.
document.querySelector('iframe').id
The bit between the quotes is what's known as a CSS selector. In this instance I'm selecting the iframe using it's element type (which is iframe), but you could use a class instead, such as document.querySelector('.thisisiframe')
.
And you can test this code all in the browser under the Console in Dev Tool.
Upvotes: 2
Reputation: 133403
You can create DOM element using $(html)
method and then use various method to get .attr()
or .prop()
var myvariable = '<iframe id="myiframe" class="thisiframe">';
var ifrme = $(myvariable);
console.log(ifrme.attr('id'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 3
Reputation: 2768
You can try something like this:
console.log($(myvariable).attr('id'));
Upvotes: 1