简体   繁体   中英

Javascript Get the children of an anchor

I want to change the src of the image inside the a tag using javascript code.For that I used this code:

 function changestyle(cat) { var el = $(cat).find('.img_box').attr('id'); console.log(el); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#" onclick="changestyle(this);" id="onc_2"> this is the first anchor <div class="">hello</div> <div class="img_box" id='gtrf'> <a href="" class="yyy" id='tttt'> <img src="images/arrows_list.png" class="c1"/> image1 to be changed </a> </div> </a> <a href="#" onclick="changestyle(this);" id="onc_2"> this is second anchor <div class="">hello</div> <div class="img_box" id='gtrf'> <a href="" class="yyy" id='tttt'> <img src="images/arrows_list.png" class="c1"/> image2 to be changed with the onclick action </a> </div> </a> 

But I always get undefined in the console. When I remove the <a> inside the clicked <a> it works. Is there any way to change the src of the image by clicking on the first <a> ?

First of all you should check your general html-markup.

IDs have to be unique in its scope, see here for furhter information. You should use classes instead.

<a href="#" id="onc_2" class="anchor">
  <div class="">lol</div> 
  <div class="img_box" id='gtrf'>
      <img src="your/src.png" class="c1"/>
  </div>
</a>

I removed the second a -tag here, according to the w3c-specification

As you are using jQuery anyways, I would recommend to avoid inline-javascript.

$('.anchor').on('click', function(){

    var el = $(this).find('.img_box').attr('id');    
    var el = $(this).find('.img_box img').attr('src', new_src);   
    console.log(el);    

});

Demo

Reference

.on()

Use this:

HTML:

<a href="#"  onclick="changestyle(this);" id="onc_2">mmm
<div class="">lol</div> 
<div class="img_box" id='gtrf'>
 <a href="" class="yyy" id='tttt'>
  <img src="images/arrows_list.png" id="target-image" class="c1"/>hhh
 </a>
</div>

Javascript:

var targetLink = document.getElementById('onc_2');
var targetImage = document.getElementById('target-image');

targetLink.addEventListener('click', function(){
  targetImage.src = yourNewImageSrc;
}, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM