Get text of specific element by ID using $(this) keyword - javascript

I have several boxes and inside each of the boxes I have different title and headline elements.
I would like to know how I can get the text of the desired element inside the corresponding box that has been clicked, not all of the text elements.
Here's what I'm working with:
box.onclick = function(){
alert($(this).text());
};
This displays all of the text elements data in the alert box. I would like to solely target a single specified text element that has an id to get the text from it instead.
Any help would be appreciated.

You can use find() to target the child element:
$('.box').on('click', function() {
console.log($(this).find('h3').text())
})
.box{
background: #adadad;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='boxes'>
<div class='box'>
<h3>title 1</h3>
<h4>subtitle 1</h4>
</div>
<div class='box'>
<h3>title 2</h3>
<h4>subtitle 2</h4>
</div>
<div class='box'>
<h3>title 3</h3>
<h4>subtitle 3</h4>
</div>
</div>

HTML
<div id = "content">
<div id = "box">
<p>This is the box content 1 </p>
</div>
<div id = "box">
<p>This is the box content 2</p>
</div>
</div>
JS
$('*[id*=box]:visible').each(function(index) {
$(this).click(function() {
alert($(this).text());
});
});
Test it here:
https://codepen.io/bmvr/pen/WMZPXW

Related

Background url from href

I am trying to get url from href and paste it in background image.
The problem is that it is applying to just first div not on all div. Is this possible without giving unique classes?
HTML
<div id="main-bg"> text
<div id="inner-content"> </div>
</div>
<div id="main-bg"> text
<div id="inner-content"> </div>
</div>
<div id="main-bg"> text
<div id="inner-content"> </div>
</div>
<div id="main-bg"> text
<div id="inner-content"> </div>
</div>
JS
$('#main-bg').css(
'background-image', 'url(' + $('#inner-content a').attr('href') + ')'
);
JSFIDDLE: https://jsfiddle.net/pr07zymf/
An id MUST be unique to each element! Using it multiple times may work at times in CSS, though, JavaScript isn't so forgiving. The reason only the first <div> is styled is because JavaScript ignores all other elements with the same id.
You can use classes instead as shown in the example below!
Example Code:
/* Iterate over every element having the given class. */
$('.main-bg').each(function (index, element) {
/* Cache a jQuery instance of the element. */
var el = $(element);
/* Get the 'href' and assign it as the 'background-image' for each element. */
el.css('background-image', 'url(' + el.find('.inner-content a').attr('href') + ')');
});
.main-bg {color: #fff}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-bg"> text
<div class="inner-content">
</div>
</div>
<div class="main-bg"> text
<div class="inner-content">
</div>
</div>
<div class="main-bg"> text
<div class="inner-content">
</div>
</div>
<div class="main-bg"> text
<div class="inner-content">
</div>
</div>
When you are using HTML, please remember, the ID should always be UNIQUE.
You cannot make them the same name like "main-bg".
Solutions:
1, change their id's name to <div id ="main-bg1">, <div id ="main-bg2">, <div id ="main-bg3">, and <div id ="main-bg4">
2, use CLASS like
<div class="main-bg"> text
<div class="inner-content"> </div>
And remember, every time when you do
$('#ID')
or
document.getElementById(ID)
It will always choose the FIRST element which has this ID.

JS / jQuery - How together innerHTML of targeted element of a certain class and append /replace it?

I want to get the text on click with a certain class but nothing works. I have a div with 2 p tags and I want to get both separate. Also, I want to append them. .append() appends but just keeps adding all targeted events. empty().append() gives me random results (on first click it works, on second I get half of the text etc). Ive tried most of what I could find on stack overflow but nothing helped. Any help would be great!
Ive tried:
$(event.target).text(); //that gives me the text, but not both p elements separate
$(this).hasClass('.video-title'); //only returns to me true/false
var title= document.getElementsByClassName("video-title")[0].innerHTML; //doesn't give me the current element.
$('p.video-title').innerHTML; //doesnt help either
HTML
<div class="video-container">
<iframe id="vid_frame" src="https://www.youtube.com/embed/xxx?rel=0&showinfo=0&autohide=1" width="900" height="450"></iframe>
<div id="video-info"></div>
</div>
<div class="col-sm-4 video-col">
<div class="video-wrapper" onClick="attachSrc('yyy', event)">
<img src="assets/images/thumbnail/yourHeart_official.jpg" width="260" height="160">
<div class="overlay">
<p class="video-title">title 1</p>
<p class="video-author">author 1</p>
</div>
</div>
</div>
<div class="col-sm-4 video-col">
<div class="video-wrapper" onClick="attachSrc('xxx', event)">
<img src="assets/images/thumbnail/yourHeart_karaoke.jpg" width="260" height="160">
<div class="overlay">
<p class="video-title">title 2</p>
<p class="video-author">author 2</p>
</div>
</div>
</div>
<script>
function attachSrc(id, event) {
var text = $(event.target).text();
$('#video-info').append(text);
}
</script>
As you are using jQuery, I would recommend you to use unobtrusive event handler and use .on() to attach event handlers.
Here in example I have attached event with wrapper element and DOM traversal method to traverse and target desired element.
And to persists arbitrary data use data-* prefixed custom attribute which can be fetched using .data(key)
<div class="video-wrapper" data-id="yyy">
Script
$('.video-col').on('click', '.video-wrapper', function() {
var elem = $('#video-info').empty();
var title = $(this).find('.video-title').text();
elem.append(title);
console.log(title);
var author= $(this).find('.video-author').text();
elem.append(author);
console.log(author);
console.log($(this).data('id'));// To fetch custom data associated with element
});
$(function() {
$('.video-col').on('click', '.video-wrapper', function() {
console.clear();
var elem = $('#video-info').empty();
var title = $(this).find('.video-title').text();
elem.append(title);
console.log(title);
var author = $(this).find('.video-author').text();
elem.append(author);
console.log(author);
console.log($(this).data('id')); // To fetch custom data associated with element
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="video-container">
<div id="video-info"></div>
</div>
<div class="col-sm-4 video-col">
<div class="video-wrapper" data-id="yyy">
<img src="assets/images/thumbnail/yourHeart_official.jpg" width="260" height="160">
<div class="overlay">
<p class="video-title">title 1</p>
<p class="video-author">author 1</p>
</div>
</div>
</div>
<div class="col-sm-4 video-col">
<div class="video-wrapper" data-id="xxx">
<img src="assets/images/thumbnail/yourHeart_karaoke.jpg" width="260" height="160">
<div class="overlay">
<p class="video-title">title 2</p>
<p class="video-author">author 2</p>
</div>
</div>
</div>

how to select all elements with matching attribute of this in jQuery?

I would like to select all elements within a div that have the same attribute as the selected element, using the this selector.
So in my example, when I click on an element with a class of .foo, I would like to find all elements within .container that share the same data-index attribute as the element that was clicked and then add the class of .bah. Currently the function I have only adds .bah to the element that was clicked on, I understand how to select certain attributes but not in relation to the this selector.
Javascript:
$(document).on('click','.foo', function() {
$(this).addClass('bah');
});
HTML:
<div class="container">
<div class="inner1">
<div data-index="0" class="foo">
<p>item 1</p>
</div>
<div data-index="2" class="foo">
<p>item 2</p>
</div>
</div>
<div class="inner2">
<div data-index="0" class="foo">
<p>item 1</p>
</div>
<div data-index="2" class="foo">
<p>item 2</p>
</div>
</div>
</div>
You can use .filter() to get the result.
$(document).on('click','.foo', function() {
var dataIndex = $(this).data('index');
$('.container div').filter(function(){
return $(this).data('index') === dataIndex
}).addClass('bah');
});
Or using attribute based selector.
$(document).on('click','.foo', function() {
var dataIndex = $(this).data('index');
$('.container div[data-index="'+dataIndex+'"]').addClass('bah');
});
$(document).on('click','.foo', function() {
var dataIndex = $(this).data('index');
$(document).find("div[data-index='" + dataIndex + "']").each(function() {
$(this).addClass('bah');
});
});
Example Fiddle: http://jsfiddle.net/9huw0ym9/1/

Selecting the h2 element based on a clicked parent

I have a div called "panel" with multiple child elements, each with a class of poster. Each poster will be a card displaying restaurant information. I want to target the h2 for whichever poster the user clicks on, irrespective of which area of the poster they click. I'm using event delegation on the panel but I'm not sure how to target the h2.
HTML:
<div class="panel">
<div class="poster">
<div class="wrapper">
<p class="time">6-7:30PM</p>
<div class="inner-wrapper">
<h2 class="restaurant-title">Restaurant A</h2>
<h3 class="deal-description">bla bla bla</h3>
</div>
</div>
</div>
<div class="poster">
<div class="wrapper">
<p class="time">2-4:30PM</p>
<div class="inner-wrapper">
<h2 class="restaurant-title">Restaurant B</h2>
<h3 class="deal-description">bla bla bla</h3>
</div>
</div>
</div>
<div class="poster">
<div class="wrapper">
<p class="time">1-5:30PM</p>
<div class="inner-wrapper">
<h2 class="restaurant-title">Restaurant C</h2>
<h3 class="deal-description">bla bla bla</h3>
</div>
</div>
</div>
</div>
JS:
var panel = document.querySelector(".panel");
panel.addEventListener("click", handleClick);
use queryselector() in javascript
function handleClick(){
var h2=this.querySelector("h2");
}
Demo
Using jquery:
$(".panel").click(function(){
var h2 = $(this).find('h2');
});
Try this :
$(document).ready(function(){
$(".poster").click(function(){
var h2 = $(this).children(".restaurant-title");
//alert(h2.context.innerText);
})
})
Example on jsfiddle: https://jsfiddle.net/ar1xawku/
Don't forget include jquery library in your code
so i figured out a solution for this, and thought i'd share:
$(".poster").click(function(){
var h2 = $(this).find('h2');
var restaurantTitle = (h2["0"].innerText);

How do I move identical elements from one div to another with jQuery?

With the example below, I'd like to select the contents of the < h3 > tags for each block, and move them inside the 'title' divs (without the h3 tags). Is this possible?
<div id="block1">
<div class="title">
</div>
<div class="content">
<h3>Title 1</h3>
</div>
</div>
<div id="block2">
<div class="title">
</div>
<div class="content">
<h3>Title 2</h3>
</div>
</div>
Online demo: http://jsbin.com/ezuxo
// Cycle through each <div class="content"></div>
$(".content").each(function(){
// Find its first h3 tag, and remove it
var heading = $("h3", this).remove();
// Set the text of the h3 tag to the value of the previous div (.title)
$(this).prev().html($(heading).html());
});
First off, I'd assign a class to the "blocks", let's call it "block" for now. Then do this:
$(".block").each(function() {
$(".title", this).html($(".content h3", this).html());
}

Categories

Resources