1

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?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278

5 Answers5

3

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>
Satpal
  • 132,252
  • 13
  • 159
  • 168
2

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.

alex
  • 1,042
  • 4
  • 18
  • 33
1

You can try something like this:

console.log($(myvariable).attr('id'));
CodeThing
  • 2,580
  • 2
  • 12
  • 25
1

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>
Priya Goud
  • 95
  • 7
1

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)
M Usama Alvi
  • 187
  • 1
  • 15