Get Src From Image Inside Button That You Have Clicked.
I am trying to get the SRC from an image inside a button that i have to press to open a accordion (bootstrap). What I want, is to get the src from the image that is inside the butt
Solution 1:
First don't use inline JavaScript. Instead bind to the element you need. Then use this
, .find()
, and .attr()
to get the image's src
property, $(this).find('img').attr('src')
:
$('button.btn.btn-link').click(function() {
console.log($(this).find('img').attr('src'))
})
#collapseimg {
width: 15px;
}
<!-- Required meta tags --><metacharset="utf-8"><metaname="viewport"content="width=device-width, initial-scale=1, shrink-to-fit=no"><!-- Bootstrap CSS --><linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"><divid="accordion"><divclass="card"><divclass="card-header"id="headingOne"><h5class="mb-0"><buttonclass="btn btn-link"data-toggle="collapse"data-target="#collapseOne"aria-expanded="true"aria-controls="collapseOne"><imgid="collapseimg"src="collapse-close.png" />
Is het nodig een afspraak te maken?
</button></h5></div><divid="collapseOne"class="collapse"aria-labelledby="headingOne"data-parent="#accordion"><divclass="card-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</div></div></div></div><!-- Optional JavaScript --><scriptsrc="main.js"></script><!-- jQuery first, then Popper.js, then Bootstrap JS --><scriptsrc="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
Solution 2:
As IDs have to be unique in the document, you could simply use:
var button = document.getElementById("collapseimg");
var hrefVal = button.getAttribute("src");
If you have multiple buttons and you want to fetch the image within the clicked button (without using any IDs) you can do that via the click event.
var handleClick = function(event) {
var buttonClicked = event.target;
// using jQuery here, since mentioned in your tags:var imageSrc = $(buttonClicked).find("img").eq(0).attr("src");
}
And i have to concur with j08691. Don't use inline JS.
Post a Comment for "Get Src From Image Inside Button That You Have Clicked."