estevan gomez estevan gomez - 7 months ago 11
Javascript Question

Jquery Dynamic property

I have this code:

$('.myClass')[0].src += "somethinghere";


And I also have multiple Div's with myClass.

How can I have the [0] to by relevant to the selected Div?

For example:

$('.myClass')[this].src += "somethinghere";


Here is the js:

$(document).ready(function() {

$(document).on("mouseover",".myClass",function(){

//code here

});

});


The HTML is :

<div>
<a class="myLinkClass" href="" target="_blank">Hover Here</a>
<div class="box">
<iframe class="myIframeClass" width="260" height="150" src="" frameborder="0"></iframe>
</div>
</div>

<div>
<a class="myLinkClass" href="" target="_blank">Hover Here</a>
<div class="box">
<iframe class="myIframeClass" width="260" height="150" src="" frameborder="0"></iframe>
</div>
</div>

<div>
<a class="myLinkClass" href="" target="_blank">Hover Here</a>
<div class="box">
<iframe class="myIframeClass" width="260" height="150" src="" frameborder="0"></iframe>
</div>
</div>


What seems to work everytime is:

$('.myIframeClass')[0].src += "something";


but it will only work for the first iframe and not for the others

Answer

You could use the this directly
update: after the updated answer (with the real html) it turns out you need to use the closest method to find the container div and then the .find to locate the actual iframe

$(document).ready(function() {
  $(document).on("mouseover", ".myLinkClass", function() {
    var iframe = $(this).closest('div').find('iframe').get(0);
    iframe.src += 'something%20';
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div>
  <a class="myLinkClass" href="" target="_blank">Hover Here</a>
  <div class="box">
    <iframe class="myIframeClass" width="260" height="150" src="http://urlecho.appspot.com/echo?body=frame-1" frameborder="0"></iframe>
  </div>
</div>

<div>
  <a class="myLinkClass" href="" target="_blank">Hover Here</a>
  <div class="box">
    <iframe class="myIframeClass" width="260" height="150" src="http://urlecho.appspot.com/echo?body=frame-2" frameborder="0"></iframe>
  </div>
</div>

<div>
  <a class="myLinkClass" href="" target="_blank">Hover Here</a>
  <div class="box">
    <iframe class="myIframeClass" width="260" height="150" src="http://urlecho.appspot.com/echo?body=frame-3" frameborder="0"></iframe>
  </div>
</div>


Keep in mind that div elements do not have a src property.

If they are indeed div elements you might want to use the .attr method instead.

$(document).ready(function() {
        $(document).on("mouseover",".myClass",function() {
           var element = $(this),
               currentSrc = $(this).attr('src');

           element.attr('src', currentSrc + 'something');
        });      
});