Reputation: 596
I need to translate this jQuery code into javascript for use in Google Tag Manager, but I'm having some trouble with the translation:
$('.book-wrapper').click(function() {return( $('.book-title', this).text() )});
Any help is much appreciated. Thanks!
Upvotes: 0
Views: 142
Reputation: 35670
Use document.querySelectorAll() to grab all the elements with the book-wrapper
class:
var wrappers= document.querySelectorAll('.book-wrapper');
Iterate through the collection, adding click handlers. Use this.querySelector() to grab the title of the clicked book-wrapper
:
for(var i = 0 ; i < wrappers.length ; i++) {
wrappers[i].addEventListener('click', function(e) {
var title= this.querySelector('.book-title').textContent;
console.log(title);
return title;
});
}
var wrappers= document.querySelectorAll('.book-wrapper');
for(var i = 0 ; i < wrappers.length ; i++) {
wrappers[i].addEventListener('click', function(e) {
var title= this.querySelector('.book-title').textContent;
console.log(title);
return title;
});
}
.book-wrapper {
box-shadow: 10px 10px 5px 0px rgba(0,0,0,0.75);
margin-bottom: 2em;
border: 1px solid #666;
}
<div class="book-wrapper">
<div class="book-title">The Little Prince</div>
<div>
This is the story about a little prince.
</div>
</div>
<div class="book-wrapper">
<div class="book-title">The Little Mermaid</div>
<div>
This is the story about a little mermaid.
</div>
</div>
Upvotes: 1
Reputation: 12129
Something like the below should work for you
<div class="book-wrapper">Click here to see name of the book</div>
<div class="book-title">Lord of the Rings</div>
<script type="text/javascript">
var bookWrapper = document.getElementsByClassName('book-wrapper');
for (var x = 0; x < bookWrapper.length; x++) {
bookWrapper[x].addEventListener('click', getText);
}
function getText() {
alert(document.getElementsByClassName('book-title')[0].innerHTML);
return document.getElementsByClassName('book-title')[0].innerHTML;
}
</script>
Upvotes: 1
Reputation: 3241
Looks like something along these lines, I think:
var els = document.querySelector('.book-wrapper');
for (var ix = 0; ix < els.length; ix++) {
els[ix].addEventListener('click', getText);
}
function getText(e) {
var titles = e.target.querySelector('.book-title');
return titles[0].innerText || null;
}
<div class="book-wrapper">
<div class="book-title">A Tale of Two Cities</div>
</div>
Upvotes: 2