The problem I am having is targeting the text in the input tag in the HTML below with Button that is Copying that text (words). What do i need to change to the JS to get it to target that Input value?
I want to do this without using ID - as I plan on replicating this many many times and don't want to set up individual Id's for the Input tags.
If there is a way to refer to the Class - 'columns-small-8' - child element, then maybe that would work?
Thanks in advance
JS
<script>
window.onload=function(){
let btns = document.getElementsByTagName("button")
Array.from(btns).forEach(ele => {
ele.addEventListener("click", function() {
jimsFunction(this)
});
})
function jimsFunction(input) {
let x = input.previousElementSibling
let ele = x.previousElementSibling
ele.select()
ele.setSelectionRange(0, 99999)
navigator.clipboard.writeText(ele.value)
alert("Copied: " ele.value)
}}
</script>
HTML
<div>
<div >
<div >
<input type="text" value="words" readonly>
</div>
<div >
<a href="www.google.com"
target="_blank">View</a>
</div>
<div >
<button type="button" >Copy URL</button>
</div>
</div>
</div>
CodePudding user response:
With your html structure, you can call to parent of it same as :
window.onload=function(){
let btns = document.getElementsByTagName("button")
Array.from(btns).forEach(ele => {
ele.addEventListener("click", function() {
jimsFunction(this)
});
})
function jimsFunction(input) {
let x = input.parentElement.parentElement
let ele = x.firstElementChild.firstElementChild
ele.select()
ele.setSelectionRange(0, 99999)
navigator.clipboard.writeText(ele.value)
alert("Copied: " ele.value)
}}
<div>
<div >
<div >
<input type="text" value="words" readonly>
</div>
<div >
<a href="www.google.com"
target="_blank">View</a>
</div>
<div >
<button type="button" >Copy URL</button>
</div>
</div>
</div>